Skip to main content

vector_core/
sending.rs

1//! Message sending — NIP-17 gift-wrapped DMs (text and file attachments).
2//!
3//! This is the core send pipeline used by all Vector interfaces (GUI, CLI, SDK).
4//! Clients provide a `SendCallback` for status notifications (pending/sent/failed/progress)
5//! and a `SendConfig` for retry/cancel behavior.
6
7use crate::event_ext::FinalizeUnsignedWithId;
8use std::ops::Range;
9use std::sync::Arc;
10use std::sync::atomic::{AtomicBool, Ordering};
11use nostr_sdk::prelude::*;
12
13/// NIP-59's gift-wrap backdating window (0 to 2 days).
14///
15/// nostr 0.45 made its own copy of this private, but the wrap timestamps we mint
16/// must stay inside the window readers expect, so it's pinned here rather than
17/// re-guessed per call site.
18pub const NIP59_RANDOM_TIMESTAMP_TWEAK: Range<u64> = 0..172_800;
19
20/// `crate::clock::timestamp()` backdated by a random offset inside the NIP-59 window.
21///
22/// 0.45.0 removed `Timestamp::tweaked`; this mirrors what nip59 does internally.
23pub fn tweaked_timestamp() -> Timestamp {
24    use ::rand::Rng;
25    let secs: u64 = ::rand::thread_rng().gen_range(NIP59_RANDOM_TIMESTAMP_TWEAK);
26    Timestamp::from_secs(crate::clock::timestamp().as_secs().saturating_sub(secs))
27}
28
29use crate::state::{nostr_client, my_public_key, STATE};
30use crate::types::{Message, Attachment};
31use crate::crypto;
32
33// ============================================================================
34// SendCallback — Client notification trait
35// ============================================================================
36
37/// Callbacks invoked during the DM send pipeline.
38///
39/// Each method has a default no-op so simple callers (CLI, bots, tests)
40/// implement only what they need. Methods are synchronous and non-fallible
41/// by design — they should never block the send pipeline.
42///
43/// Exception: `on_upload_progress` returns `Result` — return `Err` to cancel.
44pub trait SendCallback: Send + Sync {
45    /// Message created and added to STATE as pending.
46    fn on_pending(&self, _chat_id: &str, _msg: &Message) {}
47
48    /// The flag a cancel flips for this pending message, if the client keeps one.
49    /// The uploader polls it between progress ticks, so a cancel lands at once
50    /// even while nothing is moving.
51    fn cancel_token(&self, _pending_id: &str) -> Option<Arc<AtomicBool>> {
52        None
53    }
54
55    /// File upload progress. Return Err("...") to cancel the upload.
56    fn on_upload_progress(
57        &self,
58        _pending_id: &str,
59        _percentage: u8,
60        _bytes_sent: u64,
61    ) -> Result<(), String> {
62        Ok(())
63    }
64
65    /// Upload complete, attachment URL now available.
66    fn on_upload_complete(&self, _chat_id: &str, _pending_id: &str, _attachment_id: &str, _url: &str) {}
67    /// What an upload is doing before its bytes move: sealing (`"encrypting"`, with its
68    /// percentage when it is streamed) or getting underway (`"starting"`).
69    fn on_upload_stage(&self, _pending_id: &str, _stage: &str, _pct: Option<u8>) {}
70
71    /// Message successfully delivered to at least one relay.
72    /// `old_id` is the pending ID, `msg` has the real event ID.
73    fn on_sent(&self, _chat_id: &str, _old_id: &str, _msg: &Message) {}
74
75    /// Message delivery failed after all retry attempts.
76    fn on_failed(&self, _chat_id: &str, _old_id: &str, _msg: &Message) {}
77
78    /// The network in use refuses every relay the recipient reads (I2P-Only and clearnet inbox
79    /// relays, say): the send fails at once, before `on_failed`, with this one-line reason.
80    fn on_refused(&self, _chat_id: &str, _old_id: &str, _reason: &str) {}
81
82    /// Why the send failed, in one line the user can act on: called right before `on_failed`.
83    fn on_failed_reason(&self, _chat_id: &str, _old_id: &str, _reason: &str) {}
84
85    /// Persist message to database. Default is no-op.
86    /// Tauri implements this to call save_message + save_slim_chat.
87    fn on_persist(&self, _chat_id: &str, _msg: &Message) {}
88}
89
90/// No-op callback for headless/CLI/test use.
91pub struct NoOpSendCallback;
92impl SendCallback for NoOpSendCallback {}
93
94// ============================================================================
95// SendConfig — Per-call configuration
96// ============================================================================
97
98/// Configuration for a send operation.
99pub struct SendConfig {
100    /// Max gift-wrap send attempts (default: 1).
101    pub max_send_attempts: u32,
102    /// Delay between send retries (default: 5 seconds).
103    pub retry_delay: std::time::Duration,
104    /// Send copy to own inbox for recovery/sync (default: false).
105    pub self_send: bool,
106    /// Cancel token for file uploads — set to true to abort.
107    pub cancel_token: Option<Arc<AtomicBool>>,
108    /// Max Blossom upload retries per server (default: 3).
109    pub upload_retries: u32,
110    /// Delay between upload retries (default: 2 seconds).
111    pub upload_retry_delay: std::time::Duration,
112    /// NIP-40 self-destruct expiry (unix secs) to stamp on the outgoing rumor
113    /// and mirror onto the outer wrap. None = permanent. Resolved per-chat by
114    /// the caller (the "Self-Destruct Timer" setting).
115    pub expiration: Option<u64>,
116    /// A self-destruct LIFESPAN (secs) resolved at publish instead: a file send
117    /// stamps `now + lifespan` once its upload is done, so a slow upload does not
118    /// eat into the message's life. Takes precedence over `expiration` there.
119    pub self_destruct_secs: Option<u64>,
120}
121
122impl Default for SendConfig {
123    fn default() -> Self {
124        Self {
125            max_send_attempts: 1,
126            retry_delay: std::time::Duration::from_secs(5),
127            self_send: false,
128            cancel_token: None,
129            upload_retries: 3,
130            upload_retry_delay: std::time::Duration::from_secs(2),
131            expiration: None,
132            self_destruct_secs: None,
133        }
134    }
135}
136
137impl SendConfig {
138    /// Preset for GUI clients (12 retries, self-send enabled).
139    pub fn gui() -> Self {
140        Self {
141            max_send_attempts: 12,
142            self_send: true,
143            ..Default::default()
144        }
145    }
146
147    /// Preset for headless/background mode (3 retries, self-send enabled).
148    pub fn headless() -> Self {
149        Self {
150            max_send_attempts: 3,
151            self_send: true,
152            ..Default::default()
153        }
154    }
155}
156
157// ============================================================================
158// SendResult
159// ============================================================================
160
161/// Result of sending a message.
162#[derive(serde::Serialize, Clone, Debug)]
163pub struct SendResult {
164    /// The pending ID used while sending
165    pub pending_id: String,
166    /// The real event ID after successful send (None if failed)
167    pub event_id: Option<String>,
168    /// The chat ID (receiver npub for DMs)
169    pub chat_id: String,
170}
171
172// ============================================================================
173// Late-OK confirmation registry
174// ============================================================================
175//
176// A relay's OK can outlive the per-attempt wait: slow links push the
177// round-trip past nostr-sdk's OK timeout, and mobile handovers drop the
178// socket after the EVENT frame was already delivered. The wrap is then
179// on the relay while the sender believes it failed — the user re-sends
180// and the recipient sees a double-post.
181//
182// Every wrap publish registers here before its first attempt. Hosts feed
183// relay OKs back via `note_relay_ok` from their notification loop; an
184// accepted OK counts as delivery no matter how late it arrives — it wakes
185// the in-flight retry loop early, or rescues a message already marked
186// Failed back to Sent.
187
188struct WrapConfirm {
189    wrap_id: EventId,
190    chat_id: String,
191    pending_id: String,
192    /// Inner rumor id — the message's final id after finalization.
193    rumor_event_id: String,
194    rumor: UnsignedEvent,
195    callback: Arc<dyn SendCallback>,
196    self_send: bool,
197    confirmed: AtomicBool,
198    /// Claimed by whichever path (retry loop or note_relay_ok) performs
199    /// the failed→sent rescue, so it happens exactly once.
200    rescued: AtomicBool,
201    /// Set once the retry loop has exited after marking the message
202    /// failed — from then on `note_relay_ok` performs the rescue itself.
203    loop_exited: AtomicBool,
204    notify: tokio::sync::Notify,
205    /// Weak: the entry lives in this session's own scoped map, so a strong
206    /// reference would keep a swapped-out account alive forever.
207    session: std::sync::Weak<crate::db::Session>,
208    registered_at: web_time::Instant,
209}
210
211/// Entries carry this account's chat and message ids, so a late OK must only
212/// ever rescue a message in the account that sent it.
213struct WrapConfirms;
214
215fn wrap_confirms() -> Arc<std::sync::Mutex<std::collections::HashMap<EventId, Arc<WrapConfirm>>>> {
216    crate::db::current_session().scoped::<WrapConfirms, _>()
217}
218
219/// An OK this long after the last publish attempt is a ghost — drop the
220/// entry rather than resurrect a message the user has moved past.
221const WRAP_CONFIRM_TTL: std::time::Duration = std::time::Duration::from_secs(15 * 60);
222
223fn register_wrap_confirm(entry: Arc<WrapConfirm>) {
224    let owner = wrap_confirms();
225    let mut map = owner.lock().unwrap();
226    map.retain(|_, e| e.registered_at.elapsed() < WRAP_CONFIRM_TTL);
227    map.insert(entry.wrap_id, entry);
228}
229
230fn remove_wrap_confirm(wrap_id: &EventId) {
231    wrap_confirms().lock().unwrap().remove(wrap_id);
232}
233
234/// Feed a relay `OK` for an outbound event back into the send pipeline.
235///
236/// Hosts call this from their notification loop for every
237/// `RelayMessage::Ok`. Ids that aren't in-flight wraps miss the registry
238/// and return immediately.
239pub fn note_relay_ok(event_id: &EventId, accepted: bool) {
240    if !accepted {
241        return;
242    }
243    let entry = {
244        let owner = wrap_confirms();
245        let map = owner.lock().unwrap();
246        map.get(event_id).cloned()
247    };
248    let Some(entry) = entry else { return };
249    entry.confirmed.store(true, Ordering::SeqCst);
250    entry.notify.notify_one();
251    if !entry.loop_exited.load(Ordering::SeqCst)
252        || entry.rescued.swap(true, Ordering::SeqCst)
253    {
254        return;
255    }
256    if !entry.session.upgrade().is_some_and(|s| s.is_live()) {
257        remove_wrap_confirm(&entry.wrap_id);
258        return;
259    }
260    crate::db::spawn_bound(async move {
261        rescue_failed_as_sent(&entry).await;
262        remove_wrap_confirm(&entry.wrap_id);
263    });
264}
265
266/// Flip an already-failed message back to Sent — a late relay OK proved
267/// the wrap was delivered.
268async fn rescue_failed_as_sent(entry: &WrapConfirm) {
269    let finalized = {
270        let mut state = STATE.lock().await;
271        state.update_message(&entry.pending_id, |msg| {
272            msg.set_failed(false);
273        });
274        state.finalize_pending_message(&entry.chat_id, &entry.pending_id, &entry.rumor_event_id)
275    };
276    let Some((_old_id, ref msg)) = finalized else { return };
277    crate::log_info!(
278        "[Send] late relay OK confirmed wrap {} — message {} rescued to sent",
279        entry.wrap_id,
280        entry.rumor_event_id,
281    );
282    entry.callback.on_sent(&entry.chat_id, &entry.pending_id, msg);
283    entry.callback.on_persist(&entry.chat_id, msg);
284    // A late OK proved delivery — drop the retained resend body.
285    if let Some(rid) = entry.rumor.id {
286        let _ = crate::db::nip17_keys::clear_resend_payload(&rid);
287    }
288    if entry.self_send {
289        if let (Some(client), Some(my_pk)) = (nostr_client(), my_public_key()) {
290            spawn_self_send(client, my_pk, entry.rumor.clone());
291        }
292    }
293    crate::push::after_delivery(&entry.chat_id, &entry.rumor);
294}
295
296/// Fire-and-forget the self-send recovery copy + persist its wrap key.
297fn spawn_self_send(client: Client, my_pk: PublicKey, rumor: UnsignedEvent) {
298    let rid_for_self = rumor.id;
299    crate::db::spawn_bound(async move {
300        match crate::inbox_relays::send_gift_wrap_retained(
301            &client, &my_pk, rumor, [],
302        ).await {
303            Ok(self_outcome) if !self_outcome.output.success.is_empty() => {
304                if let Some(rid) = rid_for_self {
305                    if let Err(e) = crate::db::nip17_keys::store_wrap_key(
306                        &self_outcome.wrap_event_id,
307                        &rid,
308                        &my_pk,
309                        crate::db::nip17_keys::WrapRole::SelfSend,
310                        &self_outcome.wrap_secret,
311                        &self_outcome.targeted_relays,
312                    ) {
313                        eprintln!("[NIP-17] failed to persist self-wrap key: {}", e);
314                    }
315                }
316            }
317            _ => {}
318        }
319    });
320}
321
322// ============================================================================
323// Internal: retry gift-wrap send
324// ============================================================================
325
326/// Shared tail of send_dm / send_file_dm / send_rumor_dm:
327/// gift-wrap → retry loop → finalize/fail → self-send.
328///
329/// The wrap is built ONCE and the identical event republished on every
330/// attempt: a relay that already stored it answers the resend with
331/// OK-true "duplicate", so a lost OK becomes a delivery confirmation on
332/// the next attempt instead of an unconfirmed extra copy. The wrap's
333/// ephemeral key is persisted via `db::nip17_keys::store_wrap_key`
334/// BEFORE the first publish — a wrap can land without us ever seeing
335/// the OK, and the user must still be able to NIP-09 it later.
336#[allow(clippy::too_many_arguments)]
337async fn retry_send_gift_wrap(
338    client: &Client,
339    receiver: &PublicKey,
340    receiver_npub: &str,
341    pending_id: &str,
342    rumor: UnsignedEvent,
343    event_id: &str,
344    config: &SendConfig,
345    callback: Arc<dyn SendCallback>,
346    // Manual retry injects the retained wrap so the EXACT same event
347    // republishes (relay dedups the duplicate). `None` = a fresh send that
348    // builds + retains the wrap in-loop.
349    prebuilt: Option<crate::inbox_relays::BuiltGiftWrap>,
350) -> Result<SendResult, String> {
351    let my_pk = my_public_key().ok_or("Public key not set")?;
352    let inner_rumor_id = rumor.id;
353
354    // A resend already holds a persisted wrap key + retained body — don't
355    // re-store either (that would reset the row's clock and re-stash bytes).
356    let is_resend = prebuilt.is_some();
357    // Built lazily in-loop so transient signer failures (NIP-46 bunker
358    // round-trips) still get the full retry schedule; a resend seeds it.
359    let mut built: Option<crate::inbox_relays::BuiltGiftWrap> = prebuilt;
360    // Targets resolve once (again only after a lookup the network kept blind); transient
361    // inbox connections live across the whole retry window rather than reconnecting per attempt.
362    let mut targets: Option<crate::inbox_relays::GiftWrapTargets> = None;
363    let mut confirm: Option<Arc<WrapConfirm>> = None;
364    let mut last_error: Option<String> = None;
365    // Why the last attempt had nowhere to publish: the lookup couldn't reach their relays.
366    let mut unknown: Option<String> = None;
367    let mut keys_stored = is_resend;
368    // A cached inbox list is checked again at most once per send, after its relays all refused.
369    let mut rechecked = false;
370
371    let max_attempts = config.max_send_attempts.max(1);
372
373    // Too large is final: no retry makes a relay take it.
374    if let Err(why) = crate::event_size::check_rumor(&rumor) {
375        fail_pending(&callback, receiver_npub, pending_id, &why).await;
376        return Err(why);
377    }
378
379    // A network still starting is waited for once (as long as the retries would have taken, at
380    // least its ready budget), so the inbox lookup can reach the relays that list it; one that
381    // stays down fails the send with its reason.
382    if crate::transport::blocked_reason().is_some() {
383        let retries = config.retry_delay.saturating_mul(max_attempts.saturating_sub(1));
384        let budget = crate::transport::budget(crate::transport::Op::ReadyWait, std::time::Duration::ZERO).max(retries);
385        if let Err(why) = crate::transport::wait_ready(budget).await {
386            fail_pending(&callback, receiver_npub, pending_id, &why).await;
387            return Err(why);
388        }
389    }
390
391    for attempt in 0..max_attempts {
392        if built.is_none() {
393            // Mirror any NIP-40 expiry from the rumor onto the outer wrap so
394            // relays drop the gift-wrap on schedule (the inner tag is encrypted).
395            let wrap_extra: Vec<Tag> = rumor.tags.iter()
396                .find(|t| t.as_slice().first().map(|k| k.as_str() == "expiration").unwrap_or(false))
397                .cloned()
398                .into_iter()
399                .collect();
400            match crate::inbox_relays::build_gift_wrap_retained(
401                client, receiver, rumor.clone(), wrap_extra,
402            ).await {
403                Ok(b) => built = Some(b),
404                Err(e) => {
405                    crate::log_warn!(
406                        "[Send] attempt {}/{} — building gift-wrap failed: {}",
407                        attempt + 1, max_attempts, e,
408                    );
409                    last_error = Some(e);
410                    if attempt + 1 < max_attempts {
411                        crate::rt::time::sleep(config.retry_delay).await;
412                    }
413                    continue;
414                }
415            }
416        }
417        let wrap = built.as_ref().unwrap();
418
419        if confirm.is_none() {
420            let entry = Arc::new(WrapConfirm {
421                wrap_id: wrap.event.id,
422                chat_id: receiver_npub.to_string(),
423                pending_id: pending_id.to_string(),
424                rumor_event_id: event_id.to_string(),
425                rumor: rumor.clone(),
426                callback: callback.clone(),
427                self_send: config.self_send,
428                confirmed: AtomicBool::new(false),
429                rescued: AtomicBool::new(false),
430                loop_exited: AtomicBool::new(false),
431                notify: tokio::sync::Notify::new(),
432                session: std::sync::Arc::downgrade(&crate::db::current_session()),
433                registered_at: web_time::Instant::now(),
434            });
435            register_wrap_confirm(entry.clone());
436            confirm = Some(entry);
437        }
438        let confirm_ref = confirm.as_ref().unwrap();
439
440        if let Some(t) = targets.as_ref().filter(|t| t.unknown.is_none()) {
441            crate::inbox_relays::reconnect_gift_wrap_targets(t).await;
442        } else {
443            let t = crate::inbox_relays::resolve_gift_wrap_targets(client, receiver).await;
444            // A cached list the network refuses may be out of date: ask once before failing.
445            if t.refused.is_some() && t.from_cache && !rechecked {
446                rechecked = true;
447                if crate::inbox_relays::recheck_after_failure(client, receiver, &t.inbox_tried).await {
448                    continue;
449                }
450            }
451            // No retry changes a policy refusal: fail now, and say why.
452            if let Some(why) = t.refused.clone() {
453                remove_wrap_confirm(&confirm_ref.wrap_id);
454                callback.on_refused(receiver_npub, pending_id, &why);
455                fail_pending(&callback, receiver_npub, pending_id, &why).await;
456                return Err(why);
457            }
458            // Unknown is not absent: nothing is published this attempt, and the next looks again
459            // rather than landing on our own relays.
460            if let Some(why) = t.unknown.clone() {
461                crate::log_warn!("[Send] attempt {}/{} — inbox lookup out of reach: {}", attempt + 1, max_attempts, why);
462                unknown = Some(why);
463                targets = None;
464                if attempt + 1 < max_attempts {
465                    crate::rt::time::sleep(config.retry_delay).await;
466                }
467                continue;
468            }
469            unknown = None;
470            // First send only: persist the wrap key (NIP-09 delete) AND retain
471            // the exact wrap event + rumor (byte-identical resend on manual
472            // retry). A resend already holds both.
473            if !keys_stored {
474                keys_stored = true;
475                if let Some(rid) = inner_rumor_id {
476                    if let Err(e) = crate::db::nip17_keys::store_wrap_key(
477                        &wrap.event.id,
478                        &rid,
479                        receiver,
480                        crate::db::nip17_keys::WrapRole::Recipient,
481                        &wrap.secret,
482                        &t.targeted_relays,
483                    ) {
484                        eprintln!("[NIP-17] failed to persist wrap key: {}", e);
485                    }
486                    if let Err(e) = crate::db::nip17_keys::stash_resend_payload(
487                        &wrap.event.id, pending_id, &wrap.event, &rumor,
488                    ) {
489                        eprintln!("[NIP-17] failed to retain resend payload: {}", e);
490                    }
491                }
492            }
493            // A resend, or targets swapped after a re-check: a later delete must reach these too.
494            if keys_stored && (is_resend || rechecked) {
495                if let Err(e) = crate::db::nip17_keys::add_wrap_relays(&wrap.event.id, &t.targeted_relays) {
496                    eprintln!("[NIP-17] failed to note the new wrap relays: {}", e);
497                }
498            }
499            targets = Some(t);
500        }
501        let targets_ref = targets.as_ref().unwrap();
502        let from_cache = targets_ref.from_cache;
503        let inbox_tried = targets_ref.inbox_tried.clone();
504
505        match crate::inbox_relays::publish_gift_wrap_to_targets(
506            client, targets_ref, &wrap.event,
507        ).await {
508            Ok(output) if !output.success.is_empty() => {
509                return Ok(finalize_gift_wrap_sent(
510                    client, my_pk, receiver_npub, pending_id, event_id,
511                    &rumor, config, &callback, confirm_ref, targets_ref,
512                ).await);
513            }
514            Ok(output) => {
515                // The publish round-trip ran but no targeted relay confirmed
516                // (auth required, kind filter, rate-limit, timed-out OK,
517                // etc.). Surface the per-relay failure reasons so the user
518                // can see WHY their DMs aren't being accepted.
519                let failures: Vec<String> = output.failed.iter()
520                    .map(|(url, err)| format!("{}: {}", url, err))
521                    .collect();
522                crate::log_warn!(
523                    "[Send] attempt {}/{} — 0 of {} relays accepted (targeted: {}). Per-relay errors: {}",
524                    attempt + 1,
525                    max_attempts,
526                    targets_ref.targeted_relays.len(),
527                    targets_ref.targeted_relays.join(", "),
528                    if failures.is_empty() {
529                        "(none reported — likely all timed out before responding)".to_string()
530                    } else {
531                        failures.join(" | ")
532                    },
533                );
534                last_error = None;
535            }
536            Err(e) => {
537                crate::log_warn!(
538                    "[Send] attempt {}/{} — publish errored: {}",
539                    attempt + 1, max_attempts, e,
540                );
541                last_error = Some(e);
542            }
543        }
544
545        // A late OK for an earlier attempt may have arrived while this one
546        // was publishing.
547        if confirm_ref.confirmed.load(Ordering::SeqCst) {
548            return Ok(finalize_gift_wrap_sent(
549                client, my_pk, receiver_npub, pending_id, event_id,
550                &rumor, config, &callback, confirm_ref, targets_ref,
551            ).await);
552        }
553
554        // Every relay refused a list the cache served, which may be out of date: ask again, and
555        // if it changed, the next attempt goes to the new one at once.
556        if from_cache && !rechecked && attempt + 1 < max_attempts {
557            rechecked = true;
558            if crate::inbox_relays::recheck_after_failure(client, receiver, &inbox_tried).await {
559                crate::log_info!("[Send] {}'s inbox relays changed; sending to the new ones", receiver_npub);
560                if let Some(old) = targets.take() {
561                    crate::inbox_relays::teardown_gift_wrap_targets(client, &old).await;
562                }
563                continue;
564            }
565        }
566
567        if attempt + 1 < max_attempts {
568            // Sleep out the retry delay, waking instantly on a late OK
569            // (notify_one stores a permit, so an OK landing before this
570            // line still wakes us).
571            let _ = crate::rt::time::timeout(
572                config.retry_delay,
573                confirm_ref.notify.notified(),
574            ).await;
575            if confirm_ref.confirmed.load(Ordering::SeqCst) {
576                return Ok(finalize_gift_wrap_sent(
577                    client, my_pk, receiver_npub, pending_id, event_id,
578                    &rumor, config, &callback, confirm_ref, targets_ref,
579                ).await);
580            }
581        }
582    }
583
584    // No OK is no proof it didn't land: a relay seen holding the wrap is proof it did.
585    if let (Some(wrap), Some(t), Some(entry)) = (built.as_ref(), targets.as_ref(), confirm.as_ref()) {
586        if wrap_on_relays(client, &wrap.event, receiver, t).await {
587            return Ok(finalize_gift_wrap_sent(
588                client, my_pk, receiver_npub, pending_id, event_id,
589                &rumor, config, &callback, entry, t,
590            ).await);
591        }
592    }
593
594    // Exhausted every attempt with no OK observed. Mark failed, but leave
595    // the confirmation entry armed: a straggler OK can still rescue this
596    // message to Sent (see note_relay_ok).
597    if let Some(t) = targets.as_ref() {
598        crate::inbox_relays::teardown_gift_wrap_targets(client, t).await;
599    }
600    let why = crate::transport::blocked_reason()
601        .or_else(|| unknown.clone())
602        .or_else(|| built.is_none().then(|| last_error.clone()).flatten())
603        .unwrap_or_else(|| "No relay accepted the message.".to_string());
604    fail_pending(&callback, receiver_npub, pending_id, &why).await;
605    if let Some(entry) = confirm.as_ref() {
606        entry.loop_exited.store(true, Ordering::SeqCst);
607        // An OK that landed between the last attempt and loop_exited going
608        // up would see loop_exited=false and skip its rescue — catch it here.
609        if entry.confirmed.load(Ordering::SeqCst)
610            && !entry.rescued.swap(true, Ordering::SeqCst)
611        {
612            rescue_failed_as_sent(entry).await;
613            remove_wrap_confirm(&entry.wrap_id);
614            return Ok(SendResult {
615                pending_id: pending_id.to_string(),
616                event_id: Some(event_id.to_string()),
617                chat_id: receiver_npub.to_string(),
618            });
619        }
620    }
621    match last_error {
622        Some(e) => Err(format!("Failed to send DM after {} attempts: {}", max_attempts, e)),
623        None => Err(format!(
624            "Failed to send DM after {} attempts (no relays accepted the gift-wrap)",
625            max_attempts
626        )),
627    }
628}
629
630/// Whether any targeted relay holds `wrap`. One that serves gift wraps only to their
631/// recipient can't say, so silence here is no verdict.
632async fn wrap_on_relays(
633    client: &Client,
634    wrap: &Event,
635    receiver: &PublicKey,
636    targets: &crate::inbox_relays::GiftWrapTargets,
637) -> bool {
638    use futures_util::stream::{FuturesUnordered, StreamExt};
639    let filter = Filter::new().id(wrap.id).kind(Kind::GiftWrap).pubkey(*receiver);
640    let budget = crate::relay_request_timeout(std::time::Duration::from_secs(8));
641    let mut checks: FuturesUnordered<_> = targets
642        .resolved
643        .iter()
644        .map(|(url, _)| crate::community::transport::fetch_relay_eose_filters(client, url.as_str(), vec![filter.clone()], budget))
645        .collect();
646    while let Some(found) = checks.next().await {
647        if found.is_ok_and(|events| events.iter().any(|e| e.id == wrap.id)) {
648            return true;
649        }
650    }
651    false
652}
653
654/// Success epilogue shared by every confirmed path in the retry loop:
655/// finalize the pending message, notify, persist, fire the self-send.
656#[allow(clippy::too_many_arguments)]
657async fn finalize_gift_wrap_sent(
658    client: &Client,
659    my_pk: PublicKey,
660    receiver_npub: &str,
661    pending_id: &str,
662    event_id: &str,
663    rumor: &UnsignedEvent,
664    config: &SendConfig,
665    callback: &Arc<dyn SendCallback>,
666    confirm: &Arc<WrapConfirm>,
667    targets: &crate::inbox_relays::GiftWrapTargets,
668) -> SendResult {
669    remove_wrap_confirm(&confirm.wrap_id);
670    crate::inbox_relays::teardown_gift_wrap_targets(client, targets).await;
671
672    let finalized = {
673        let mut state = STATE.lock().await;
674        state.finalize_pending_message(receiver_npub, pending_id, event_id)
675    };
676    if let Some((_old_id, ref finalized_msg)) = finalized {
677        callback.on_sent(receiver_npub, pending_id, finalized_msg);
678        callback.on_persist(receiver_npub, finalized_msg);
679    }
680
681    // Delivery confirmed — drop the retained resend body (the key row stays for
682    // NIP-09). Steady-state, only genuinely-unsent messages carry a body.
683    if let Some(rid) = rumor.id {
684        let _ = crate::db::nip17_keys::clear_resend_payload(&rid);
685    }
686
687    if config.self_send {
688        spawn_self_send(client.clone(), my_pk, rumor.clone());
689    }
690    crate::push::after_delivery(receiver_npub, rumor);
691
692    SendResult {
693        pending_id: pending_id.to_string(),
694        event_id: Some(event_id.to_string()),
695        chat_id: receiver_npub.to_string(),
696    }
697}
698
699// ============================================================================
700// send_dm — Text DMs
701// ============================================================================
702
703/// Send a NIP-17 gift-wrapped text DM.
704///
705/// Flow: pending msg → callback.on_pending → build Kind 14 rumor →
706/// gift-wrap with retry → finalize → callback.on_sent → optional self-send.
707/// Our pending message into its chat. A send answers a DM request, so the pictures and
708/// wallpaper held while it waited come down now.
709async fn add_pending(receiver_npub: &str, msg: &Message) {
710    let answered = {
711        let mut state = STATE.lock().await;
712        let unanswered = crate::requests::shielded() && state.dm_unanswered(receiver_npub);
713        state.add_message_to_participant(receiver_npub, msg);
714        unanswered
715    };
716    if answered {
717        let npub = receiver_npub.to_string();
718        crate::db::spawn_bound(async move { crate::wallpaper::release_held(&npub).await });
719        crate::profile::sync::queue_profile_sync(receiver_npub.to_string(), crate::profile::sync::SyncPriority::Critical, true);
720    }
721}
722
723pub async fn send_dm(
724    receiver_npub: &str,
725    content: &str,
726    reply_to: Option<&str>,
727    config: &SendConfig,
728    callback: Arc<dyn SendCallback>,
729) -> Result<SendResult, String> {
730    let client = nostr_client().ok_or("Not logged in")?;
731    let my_pk = my_public_key().ok_or("Public key not set")?;
732
733    // device-clock: a local id, never compared with a time.
734    let pending_id = format!("pending-{}", web_time::SystemTime::now().duration_since(web_time::UNIX_EPOCH).unwrap().as_nanos());
735    // Stamped by the corrected clock, so a fast device never dates a message ahead of everyone.
736    let now = std::time::Duration::from_millis(crate::clock::now_ms());
737
738    let receiver = PublicKey::from_bech32(receiver_npub)
739        .map_err(|e| format!("Invalid npub: {}", e))?;
740
741    let (plain, text_spans) = crate::text_spans::extract_own(content);
742    let content = plain.as_str();
743
744    // NIP-30: resolve any `:shortcode:` in the outbound text against the
745    // user's subscribed packs so the rumor carries `["emoji", ...]` tags.
746    // Recipients without the pack subscribed still render correctly, and
747    // our own-view echo populates `emoji_tags` for the renderer.
748    let emoji_tags = crate::emoji_packs::resolve_outbound_emoji_tags(content);
749
750    // Build pending message and add to state
751    let mut msg = Message {
752        id: pending_id.clone(),
753        content: content.to_string(),
754        replied_to: reply_to.unwrap_or("").to_string(),
755        at: now.as_millis() as u64,
756        pending: true,
757        mine: true,
758        npub: my_pk.to_bech32().ok(),
759        emoji_tags: emoji_tags.clone(),
760        text_spans: text_spans.clone(),
761        expiration: config.expiration,
762        ..Default::default()
763    };
764    // The quote rides the message itself: the parent may be nowhere in the UI's memory.
765    let _ = crate::db::events::populate_reply_context(&mut msg).await;
766
767    add_pending(receiver_npub, &msg).await;
768
769    callback.on_pending(receiver_npub, &msg);
770
771    // Build the rumor
772    let milliseconds = now.as_millis() % 1000;
773    // NIP-17 rumor: kind 14 + recipient p-tag (upstream's `make_rumor` is private).
774    let mut rumor = EventBuilder::new(Kind::PrivateDirectMessage, content)
775        .custom_created_at(Timestamp::from_secs(now.as_secs()))
776        .tag(Tag::public_key(receiver));
777
778    if let Some(reply_id) = reply_to {
779        if !reply_id.is_empty() {
780            rumor = rumor.tag(Tag::custom(
781                "e",
782                [reply_id.to_string(), String::new(), "reply".to_string()],
783            ));
784        }
785    }
786
787    let mut rumor = rumor.tag(Tag::custom("ms", [milliseconds.to_string()]));
788    for et in &emoji_tags {
789        rumor = rumor.tag(Tag::custom(
790            "emoji",
791            [et.shortcode.clone(), et.url.clone()],
792        ));
793    }
794    rumor = rumor.tags(crate::text_spans::to_nostr_tags(&text_spans));
795    // NIP-40 self-destruct: stamp the rumor so compliant receivers honor the
796    // expiry; retry_send_gift_wrap mirrors it onto the outer wrap for relays.
797    if let Some(exp) = config.expiration {
798        rumor = rumor.tag(Tag::expiration(Timestamp::from_secs(exp)));
799    }
800    let built_rumor = rumor.finalize_unsigned_with_id(my_pk);
801    let event_id = built_rumor.id.ok_or("Rumor has no id")?.to_hex();
802
803    // Send via gift-wrap with retry
804    retry_send_gift_wrap(
805        &client, &receiver, receiver_npub, &pending_id,
806        built_rumor, &event_id, config, callback, None,
807    ).await
808}
809
810// ============================================================================
811// send_rumor_dm — Pre-built rumor (custom events)
812// ============================================================================
813
814/// Send a pre-built rumor via NIP-17 gift-wrap.
815///
816/// Used when the caller has already built the rumor. Skips encryption/upload.
817pub async fn send_rumor_dm(
818    receiver_npub: &str,
819    pending_id: &str,
820    rumor: UnsignedEvent,
821    config: &SendConfig,
822    callback: Arc<dyn SendCallback>,
823) -> Result<SendResult, String> {
824    let client = nostr_client().ok_or("Not logged in")?;
825
826    let receiver = PublicKey::from_bech32(receiver_npub)
827        .map_err(|e| format!("Invalid npub: {}", e))?;
828
829    let event_id = rumor.id.ok_or("Rumor has no id")?.to_hex();
830
831    retry_send_gift_wrap(
832        &client, &receiver, receiver_npub, pending_id,
833        rumor, &event_id, config, callback, None,
834    ).await
835}
836
837/// Manually retry a failed DM by republishing the EXACT retained recipient
838/// wrap. Same outer event id → relays no-op the duplicate, so a first send
839/// that silently landed can never double-post, regardless of the recipient's
840/// client.
841///
842/// `Ok(true)`  — a retained wrap was found and the resend went through the
843///               normal retry loop (message ends sent, or red again ready to
844///               retry). The caller must NOT fall back.
845/// `Ok(false)` — nothing retained (old/pruned message, or the first send
846///               failed before a wrap was ever built, e.g. an upload error).
847///               The caller falls back to a fresh send — safe, since no wrap
848///               reached a relay in that case.
849pub async fn resend_failed_dm(
850    receiver_npub: &str,
851    failed_msg_id: &str,
852    config: &SendConfig,
853    callback: Arc<dyn SendCallback>,
854) -> Result<bool, String> {
855    // Guard the read→flip→republish against a mid-tap account swap: the payload
856    // is this account's; a swap before the STATE flip must abort (returning
857    // "handled" so the caller never falls back to a fresh send in the WRONG
858    // account). retry_send_gift_wrap re-guards its own STATE/DB writes.
859    let payload = match crate::db::nip17_keys::get_resend_payload_by_pending(failed_msg_id)? {
860        Some(p) => p,
861        None => return Ok(false),
862    };
863    let client = nostr_client().ok_or("Not logged in")?;
864    let receiver = PublicKey::from_bech32(receiver_npub)
865        .map_err(|e| format!("Invalid npub: {}", e))?;
866
867    // Flip the red row back to "sending"; the retry loop's own fail/finalize
868    // path returns it to red or promotes it to sent.
869    let repending = {
870        let mut state = STATE.lock().await;
871        state.update_message(failed_msg_id, |msg| {
872            msg.set_failed(false);
873            msg.set_pending(true);
874        })
875    };
876    if let Some((_chat_id, ref msg)) = repending {
877        callback.on_pending(receiver_npub, msg);
878    }
879
880    let event_id = payload.rumor.id.ok_or("Retained rumor has no id")?.to_hex();
881    let built = crate::inbox_relays::BuiltGiftWrap {
882        event: payload.wrap_event,
883        secret: payload.secret,
884    };
885    // Inject the retained wrap: the loop republishes these exact bytes.
886    if let Err(e) = retry_send_gift_wrap(
887        &client, &receiver, receiver_npub, failed_msg_id,
888        payload.rumor, &event_id, config, callback, Some(built),
889    )
890    .await
891    {
892        // The resend was attempted — the loop already marked the row red again.
893        // Still "handled": the caller must not fall back to a fresh wrap, or the
894        // retained wrap that may yet be sitting on a relay would double-post.
895        crate::log_warn!("[Send] idempotent resend of {} did not land: {}", failed_msg_id, e);
896    }
897    Ok(true)
898}
899
900// ============================================================================
901// send_file_dm — File Attachment DMs
902// ============================================================================
903
904/// Send a NIP-17 gift-wrapped file attachment DM.
905///
906/// Flow: hash → save locally → pending → encrypt → upload → build Kind 15 rumor → gift-wrap + send.
907#[allow(clippy::too_many_arguments)]
908pub async fn send_file_dm(
909    receiver_npub: &str,
910    file_bytes: Arc<Vec<u8>>,
911    filename: &str,
912    extension: &str,
913    content: Option<&str>,
914    reply_to: Option<&str>,
915    config: &SendConfig,
916    callback: Arc<dyn SendCallback>,
917) -> Result<SendResult, String> {
918    send_file_dm_with_meta(receiver_npub, file_bytes, filename, extension, None, content, reply_to, config, callback).await
919}
920
921/// [`send_file_dm`] for a caller that already holds the image's preview metadata,
922/// sparing a second full decode before the bubble can appear. `None` derives it.
923#[allow(clippy::too_many_arguments)]
924pub async fn send_file_dm_with_meta(
925    receiver_npub: &str,
926    file_bytes: Arc<Vec<u8>>,
927    filename: &str,
928    extension: &str,
929    img_meta: Option<crate::types::ImageMetadata>,
930    content: Option<&str>,
931    reply_to: Option<&str>,
932    config: &SendConfig,
933    callback: Arc<dyn SendCallback>,
934) -> Result<SendResult, String> {
935    send_file_dm_from(receiver_npub, FileSource::Bytes(file_bytes), filename, extension, img_meta, content, reply_to, config, callback).await
936}
937
938/// Where an outgoing file's bytes come from.
939pub enum FileSource {
940    /// In memory: images the caller has already processed, pasted bytes.
941    Bytes(Arc<Vec<u8>>),
942    /// On disk, read a chunk at a time: a file of any size costs one chunk of memory.
943    /// Its preview metadata is the caller's to give; nothing here decodes it.
944    Path(std::path::PathBuf),
945    /// A copy this app already saved in the download folder (a failed send's, retried):
946    /// sent from where it is, since copying it again would only leave a duplicate.
947    Saved(std::path::PathBuf),
948    /// Our own ciphertext of an upload that failed, kept to go again as it is: the same blob,
949    /// under the key and nonce it was sealed with.
950    Sealed { path: std::path::PathBuf, hash: String, key: String, nonce: String, blob_sha256: String },
951}
952
953/// Removes a file when dropped: the ciphertext of an upload that ended either way.
954pub struct TempFile(std::path::PathBuf);
955
956impl Drop for TempFile {
957    fn drop(&mut self) {
958        let _ = std::fs::remove_file(&self.0);
959    }
960}
961
962impl TempFile {
963    /// Keep the file after all: a failed upload's ciphertext, for its retry.
964    pub fn keep(self) -> std::path::PathBuf {
965        let path = self.0.clone();
966        std::mem::forget(self);
967        path
968    }
969}
970
971/// Where a send's ciphertext waits for its upload, and a failed one for its retry.
972#[cfg(not(target_arch = "wasm32"))]
973fn outgoing_dir() -> std::path::PathBuf {
974    crate::db::current_account_dir().map(|d| d.join("outgoing")).unwrap_or_else(|_| std::env::temp_dir())
975}
976
977/// A failed upload's ciphertext, kept for its retry: written out when it was sealed in memory.
978#[cfg(not(target_arch = "wasm32"))]
979pub fn keep_for_retry(body: &crate::blossom::UploadBody, guard: Option<TempFile>, hash: &str, key: &str, nonce: &str, pending_id: &str, mime: &str) {
980    let path = match (body, guard) {
981        (crate::blossom::UploadBody::File { .. }, Some(guard)) => guard.keep(),
982        (crate::blossom::UploadBody::Memory(data), _) => {
983            let dir = outgoing_dir();
984            let _ = std::fs::create_dir_all(&dir);
985            let path = dir.join(format!("{hash}-{pending_id}.enc"));
986            if std::fs::write(&path, &***data).is_err() {
987                return;
988            }
989            path
990        }
991        _ => return,
992    };
993    crate::media::pending::sealed(crate::simd::hex::hex_to_bytes_32(hash), path, key, nonce, mime);
994}
995
996/// What a failed send of `att` can go again from, best first: the sender's own file, the
997/// bytes this account still holds, or the ciphertext its failed upload kept.
998#[cfg(not(target_arch = "wasm32"))]
999pub fn retry_source(att: &Attachment) -> Option<FileSource> {
1000    let hash = crate::simd::hex::hex_to_bytes_32_checked(&att.id)?;
1001    if let Some(path) = crate::media::pending::plain_path(&hash) {
1002        return Some(FileSource::Path(path));
1003    }
1004    if crate::media::ram::cache().contains(&hash) || crate::media::store::holds(&hash) {
1005        let src = crate::media::open(&hash)?;
1006        return crate::media::read_all(&*src).ok().map(|bytes| FileSource::Bytes(Arc::new(bytes)));
1007    }
1008    let prefix = format!("{}-", att.id);
1009    let kept = std::fs::read_dir(outgoing_dir())
1010        .ok()?
1011        .flatten()
1012        .filter(|e| e.file_name().to_string_lossy().starts_with(&prefix) && e.file_name().to_string_lossy().ends_with(".enc"))
1013        .max_by_key(|e| e.metadata().and_then(|m| m.modified()).ok())?;
1014    let (blob_sha256, _) = crypto::stream::hash_file(&kept.path()).ok()?;
1015    Some(FileSource::Sealed { path: kept.path(), hash: att.id.clone(), key: att.key.clone(), nonce: att.nonce.clone(), blob_sha256 })
1016}
1017
1018/// Give up on a failed send for good. Its uploads leave the media servers only once nothing
1019/// signed can still be read with them: no message was ever built, or its take-back is on a
1020/// relay. A message that failed here may have landed, or may land yet, and would point at them.
1021pub async fn abandon_failed_send(chat_id: &str, message_id: &str, attachments: &[Attachment]) {
1022    let in_community = matches!(crate::db::community::community_id_for_channel(chat_id), Ok(Some(_)));
1023    let unread = if in_community {
1024        crate::community::v2::service::discard_unconfirmed(chat_id, message_id).await
1025    } else {
1026        match crate::db::nip17_keys::get_resend_payload_by_pending(message_id) {
1027            Ok(None) => true,
1028            Ok(Some(wrapped)) => match (wrapped.rumor.id, PublicKey::from_bech32(chat_id)) {
1029                (Some(rumor_id), Ok(recipient)) => crate::deletion::take_back_failed_dm(&rumor_id, &recipient).await,
1030                _ => false,
1031            },
1032            Err(_) => false,
1033        }
1034    };
1035    if !unread {
1036        return;
1037    }
1038    let urls: Vec<String> = attachments.iter().flat_map(|a| a.all_urls().map(str::to_string)).collect();
1039    let urls = crate::db::attachments::urls_unreferenced_elsewhere(&urls, message_id).unwrap_or_default();
1040    if urls.is_empty() {
1041        return;
1042    }
1043    if let Ok(signer) = crate::signer::active_signer() {
1044        crate::blossom::delete_blobs_best_effort(signer, urls);
1045    }
1046}
1047
1048/// Forget what a failed send of `att` kept to go again: its sealed copies and its bubble's source.
1049#[cfg(not(target_arch = "wasm32"))]
1050pub fn discard_retry_copy(att: &Attachment) {
1051    let Some(hash) = crate::simd::hex::hex_to_bytes_32_checked(&att.id) else { return };
1052    crate::media::pending::forget(&hash);
1053    let prefix = format!("{}-", att.id);
1054    if let Ok(entries) = std::fs::read_dir(outgoing_dir()) {
1055        for entry in entries.flatten() {
1056            let name = entry.file_name().to_string_lossy().into_owned();
1057            if name.starts_with(&prefix) && name.ends_with(".enc") {
1058                let _ = std::fs::remove_file(entry.path());
1059            }
1060        }
1061    }
1062}
1063
1064/// Ciphertext of uploads that never went again, once it's two weeks old, and plaintext working
1065/// copies a send left behind, once they're a day old.
1066#[cfg(not(target_arch = "wasm32"))]
1067pub fn sweep_outgoing() {
1068    let dir = outgoing_dir();
1069    sweep_older_than(&dir, std::time::Duration::from_secs(14 * 24 * 3600));
1070    sweep_older_than(&dir.join("work"), std::time::Duration::from_secs(24 * 3600));
1071}
1072
1073#[cfg(not(target_arch = "wasm32"))]
1074fn sweep_older_than(dir: &std::path::Path, max_age: std::time::Duration) {
1075    let Ok(entries) = std::fs::read_dir(dir) else { return };
1076    for entry in entries.flatten() {
1077        let old = entry.metadata().and_then(|m| m.modified()).ok().and_then(|t| t.elapsed().ok()).is_some_and(|age| age > max_age);
1078        if old {
1079            let _ = std::fs::remove_file(entry.path());
1080        }
1081    }
1082}
1083
1084/// An outgoing attachment, ready for the upload.
1085pub enum Sealed {
1086    /// A live blob of these bytes already exists: the message just names it.
1087    Reused(crate::db::attachments::ReusableUpload),
1088    /// Freshly sealed. A disk body's ciphertext goes when the guard drops.
1089    Body(crate::blossom::UploadBody, Option<TempFile>),
1090}
1091
1092/// Reuse a live blob of the plaintext `hash`, or seal `plain` under `key`/`nonce`,
1093/// reporting each stage against `pending_id`. A file seals file to file, costing no memory.
1094pub async fn seal_or_reuse(
1095    plain: FileSource,
1096    hash: &str,
1097    key: &str,
1098    nonce: &str,
1099    pending_id: &str,
1100    callback: Arc<dyn SendCallback>,
1101    cancel: Option<Arc<AtomicBool>>,
1102) -> Result<Sealed, String> {
1103    // Every verified send or download of these bytes left url+key+nonce behind. Liveness
1104    // is proven, never assumed: a dead or unreachable blob falls through to a fresh upload.
1105    if let Ok(Some(r)) = crate::db::attachments::find_reusable_by_hash(hash) {
1106        if crate::blossom::blob_is_served(&r.url, std::time::Duration::from_secs(5)).await {
1107            crate::log_info!("[SmartForward] {} reused ({}, {} KB) — no upload", &hash[..8.min(hash.len())], if r.mine { "own blob" } else { "foreign blob, mirroring in background" }, r.size / 1024);
1108            return Ok(Sealed::Reused(r));
1109        }
1110    }
1111
1112    let (key, nonce) = (key.to_string(), nonce.to_string());
1113    // Resolved here, on the task that carries the account, not on a blocking thread.
1114    #[cfg(not(target_arch = "wasm32"))]
1115    let outgoing = outgoing_dir();
1116    // The web never seals from a file; wasm has no temp dir to fall back on.
1117    #[cfg(target_arch = "wasm32")]
1118    let outgoing = crate::db::current_account_dir().map(|d| d.join("outgoing")).unwrap_or_default();
1119    // Only a streamed seal can count its progress; bytes in hand are sealed in one go.
1120    callback.on_upload_stage(pending_id, "encrypting", matches!(plain, FileSource::Path(_) | FileSource::Saved(_)).then_some(0));
1121    let sealed = match plain {
1122        FileSource::Bytes(bytes) => {
1123            let sealed = crate::rt::spawn_blocking(move || {
1124                crypto::encrypt_data(&bytes, &crypto::EncryptionParams { key, nonce })
1125            })
1126            .await
1127            .map_err(|e| format!("Encryption failed: {}", e))??;
1128            Sealed::Body(crate::blossom::UploadBody::Memory(Arc::new(sealed)), None)
1129        }
1130        FileSource::Sealed { path, blob_sha256, .. } => {
1131            let len = std::fs::metadata(&path).map_err(|e| format!("Couldn't read the file: {e}"))?.len();
1132            Sealed::Body(crate::blossom::UploadBody::file(path.clone(), len, &blob_sha256)?, Some(TempFile(path)))
1133        }
1134        FileSource::Path(path) | FileSource::Saved(path) => {
1135            let _ = std::fs::create_dir_all(&outgoing);
1136            let out = outgoing.join(format!("{}-{}.enc", hash, pending_id));
1137            let guard = TempFile(out.clone());
1138            let target = out.clone();
1139            let (stage_cb, pid, plain_hash) = (callback.clone(), pending_id.to_string(), hash.to_string());
1140            // Sealed from the sender's own file, so it must still be the bytes that were hashed.
1141            let (sealed_hash, len) = crate::rt::spawn_blocking(move || {
1142                crypto::stream::encrypt_file_matching(&path, &target, &key, &nonce, &plain_hash, &mut |pct| {
1143                    stage_cb.on_upload_stage(&pid, "encrypting", Some(pct));
1144                    // A cancel lands here, not after the whole file is sealed.
1145                    !cancel.as_ref().is_some_and(|c| c.load(Ordering::Relaxed))
1146                })
1147            })
1148            .await
1149            .map_err(|e| format!("Encryption failed: {}", e))??;
1150            Sealed::Body(crate::blossom::UploadBody::file(out, len, &sealed_hash)?, Some(guard))
1151        }
1152    };
1153    callback.on_upload_stage(pending_id, "starting", None);
1154    Ok(sealed)
1155}
1156
1157/// Mark a pending message failed (in state, in the UI, on disk), saying why.
1158async fn fail_pending(callback: &Arc<dyn SendCallback>, receiver_npub: &str, pending_id: &str, why: &str) {
1159    let failed_msg = {
1160        let mut state = STATE.lock().await;
1161        state.update_message(pending_id, |msg| {
1162            msg.set_failed(true);
1163            msg.set_pending(false);
1164        })
1165    };
1166    if let Some((_chat_id, ref msg)) = failed_msg {
1167        callback.on_failed_reason(receiver_npub, pending_id, why);
1168        callback.on_failed(receiver_npub, pending_id, msg);
1169        callback.on_persist(receiver_npub, msg);
1170    }
1171}
1172
1173/// The first line of a failure, as a row can show it: a list of per-server reasons is
1174/// summed up by its heading.
1175pub fn failure_line(err: &str) -> String {
1176    let line = err.trim().trim_start_matches("Upload failed:").trim().lines().next().unwrap_or_default().trim();
1177    match line.strip_suffix(':') {
1178        Some(head) => format!("{head}."),
1179        None => line.to_string(),
1180    }
1181}
1182
1183/// Mark a pending file message failed (in state, in the UI, on disk) and hand back `err`.
1184/// Keep a sent blob in the store: the file moves in, bytes in hand are written there.
1185#[cfg(not(target_arch = "wasm32"))]
1186pub fn keep_sent(body: &crate::blossom::UploadBody, hash: &str, key: &str, nonce: &str, pt_len: u64, mime: &str) -> bool {
1187    use crate::media::store::{keep_bytes, keep_file, Keep};
1188    let keep = |blob_sha256: String| Keep {
1189        hash: crate::simd::hex::hex_to_bytes_32(hash), key: key.to_string(), nonce: nonce.to_string(),
1190        blob_sha256, pt_len, mime: mime.to_string(), origin: crate::db::media_store::Origin::Sent,
1191    };
1192    let kept = match body {
1193        crate::blossom::UploadBody::Memory(data) => keep_bytes(data, keep(crypto::sha256_hex(data))),
1194        crate::blossom::UploadBody::File { path, sha256, .. } => keep_file(path, keep(sha256.to_string())),
1195    };
1196    kept.inspect_err(|e| crate::log_warn!("[Send] sent, but couldn't keep it: {e}")).is_ok()
1197}
1198
1199async fn mark_send_failed(callback: &Arc<dyn SendCallback>, receiver_npub: &str, pending_id: &str, err: String) -> String {
1200    fail_pending(callback, receiver_npub, pending_id, &failure_line(&err)).await;
1201    err
1202}
1203
1204/// [`send_file_dm_with_meta`] from either source.
1205#[allow(clippy::too_many_arguments)]
1206pub async fn send_file_dm_from(
1207    receiver_npub: &str,
1208    source: FileSource,
1209    filename: &str,
1210    extension: &str,
1211    img_meta: Option<crate::types::ImageMetadata>,
1212    content: Option<&str>,
1213    reply_to: Option<&str>,
1214    config: &SendConfig,
1215    callback: Arc<dyn SendCallback>,
1216) -> Result<SendResult, String> {
1217    let client = nostr_client().ok_or("Not logged in")?;
1218    let my_pk = my_public_key().ok_or("Public key not set")?;
1219    let reply_to = reply_to.filter(|r| !r.is_empty());
1220    // Sign the Blossom auth event via the active client signer so bunker
1221    // accounts route through NostrConnect (the user's identity key lives on
1222    // the remote signer; MY_SECRET_KEY only holds the NIP-46 client key).
1223    let signer = crate::signer::active_signer()
1224        .map_err(|e| format!("Signer unavailable: {}", e))?;
1225
1226    // device-clock: a local id, never compared with a time.
1227    let pending_id = format!("pending-{}", web_time::SystemTime::now().duration_since(web_time::UNIX_EPOCH).unwrap().as_nanos());
1228    let now = std::time::Duration::from_millis(crate::clock::now_ms());
1229    let milliseconds = now.as_millis() % 1000;
1230
1231    let receiver = PublicKey::from_bech32(receiver_npub)
1232        .map_err(|e| format!("Invalid npub: {}", e))?;
1233
1234    let mime_type = crypto::mime_from_extension(extension);
1235
1236    // The web sends from memory only, and its bubble shows the bytes in hand.
1237    #[cfg(target_arch = "wasm32")]
1238    let (file_hash, local_path_str, img_meta, plain_len) = {
1239        let FileSource::Bytes(bytes) = &source else {
1240            return Err("Vector Web sends files from memory".into());
1241        };
1242        let file_hash = crypto::sha256_hex(bytes);
1243        let _ = crate::media::ram::insert(crate::simd::hex::hex_to_bytes_32(&file_hash), bytes.to_vec(), mime_type);
1244        let img_meta = img_meta.or_else(|| crypto::generate_image_metadata(bytes));
1245        (file_hash, String::new(), img_meta, bytes.len() as u64)
1246    };
1247    // Hash and (if not given) read the preview metadata off the runtime: each is a full
1248    // pass over the bytes, and a runtime worker parked on one stalls every task queued
1249    // behind it. Nothing is copied: the bubble reads the sender's own bytes.
1250    #[cfg(not(target_arch = "wasm32"))]
1251    let (file_hash, local_path_str, img_meta, plain_len) = {
1252        let (file_hash, img_meta, plain_len) = match &source {
1253            FileSource::Bytes(bytes) => {
1254                let bytes = Arc::clone(bytes);
1255                crate::rt::spawn_blocking(move || {
1256                    let img_meta = img_meta.or_else(|| crypto::generate_image_metadata(&bytes));
1257                    (crypto::sha256_hex(&bytes), img_meta, bytes.len() as u64)
1258                })
1259                .await
1260                .map_err(|e| format!("Attachment prep failed: {}", e))?
1261            }
1262            FileSource::Path(path) | FileSource::Saved(path) => {
1263                let path = path.clone();
1264                let (hash, len) = crate::rt::spawn_blocking(move || crypto::stream::hash_file(&path))
1265                    .await
1266                    .map_err(|e| format!("Attachment prep failed: {}", e))??;
1267                (hash, img_meta, len)
1268            }
1269            FileSource::Sealed { path, hash, .. } => {
1270                let len = std::fs::metadata(path).map_err(|e| format!("Couldn't read the file: {e}"))?.len();
1271                (hash.clone(), img_meta, len.saturating_sub(16))
1272            }
1273        };
1274        let hash = crate::simd::hex::hex_to_bytes_32(&file_hash);
1275        match &source {
1276            FileSource::Bytes(bytes) => {
1277                let _ = crate::media::ram::insert(hash, bytes.to_vec(), mime_type);
1278            }
1279            FileSource::Path(path) | FileSource::Saved(path) => crate::media::pending::plain(hash, path.clone(), mime_type),
1280            FileSource::Sealed { path, key, nonce, .. } => crate::media::pending::sealed(hash, path.clone(), key, nonce, mime_type),
1281        }
1282        (file_hash, String::new(), img_meta, plain_len)
1283    };
1284
1285    // WebXDC Mini Apps: mint the realtime-channel topic at send time and carry
1286    // it on the rumor — locally-derived topics are asymmetric in DMs (each
1287    // side's chat_id is the other party's npub), splitting players onto
1288    // disjoint gossip topics.
1289    let webxdc_topic = (extension.eq_ignore_ascii_case("xdc"))
1290        .then(|| crate::webxdc::mint_topic_id(&file_hash, &my_pk.to_hex()));
1291
1292    // The bubble goes up now, on fresh encryption parameters (a kept seal brings its own);
1293    // a reused blob swaps in its own below. AES-GCM appends a 16-byte tag, so the size is
1294    // known unencrypted.
1295    let params = match &source {
1296        FileSource::Sealed { key, nonce, .. } => crypto::EncryptionParams { key: key.clone(), nonce: nonce.clone() },
1297        _ => crypto::generate_encryption_params(),
1298    };
1299    let attachment = Attachment {
1300        id: file_hash.clone(), key: params.key.clone(), nonce: params.nonce.clone(),
1301        extension: extension.to_string(), name: filename.to_string(),
1302        url: String::new(), path: local_path_str.clone(), size: plain_len + 16,
1303        // No copy of its own: the bubble reads the sender's bytes until the send ends.
1304        img_meta: img_meta.clone(), downloading: false, downloaded: false, verified: true,
1305        resident: crate::media::resident(&crate::simd::hex::hex_to_bytes_32(&file_hash)),
1306        webxdc_topic: webxdc_topic.clone(),
1307        ..Default::default()
1308    };
1309    let mut msg = Message {
1310        id: pending_id.clone(), content: content.unwrap_or("").to_string(),
1311        replied_to: reply_to.unwrap_or("").to_string(),
1312        at: now.as_millis() as u64, pending: true, mine: true,
1313        npub: my_pk.to_bech32().ok(), attachments: vec![attachment.clone()],
1314        // A lifespan is stamped after the upload; the bubble shows no clock until then.
1315        expiration: if config.self_destruct_secs.is_some() { None } else { config.expiration },
1316        ..Default::default()
1317    };
1318    let _ = crate::db::events::populate_reply_context(&mut msg).await;
1319    add_pending(receiver_npub, &msg).await;
1320    callback.on_pending(receiver_npub, &msg);
1321    let cancel = config.cancel_token.clone().or_else(|| callback.cancel_token(&pending_id));
1322
1323    // Encrypt and upload, or reference a live blob of the same bytes and skip both.
1324    let plain = source;
1325    let sealed = match seal_or_reuse(plain, &file_hash, &params.key, &params.nonce, &pending_id, callback.clone(), cancel.clone()).await {
1326        Ok(sealed) => sealed,
1327        // The bubble is up: a seal that fails (or is cancelled) must say so, not stay pending.
1328        Err(e) => return Err(mark_send_failed(&callback, receiver_npub, &pending_id, e).await),
1329    };
1330    // Held to the end of the send, so the ciphertext goes however it ends, unless a failed
1331    // upload keeps it for the retry.
1332    #[cfg_attr(target_arch = "wasm32", allow(unused_variables))]
1333    let (reused, encrypted, ciphertext_file) = match sealed {
1334        Sealed::Reused(r) => (Some(r), None, None),
1335        Sealed::Body(body, guard) => (None, Some(body), guard),
1336    };
1337    let (att_key, att_nonce, att_url, encrypted_size) = match (&reused, &encrypted) {
1338        (Some(r), _) => {
1339            let adopted = crate::compact::CompactAttachment::from_attachment(&Attachment {
1340                key: r.key.clone(), nonce: r.nonce.clone(), url: r.url.clone(), size: r.size,
1341                ..attachment.clone()
1342            });
1343            let mut state = STATE.lock().await;
1344            state.update_message(&pending_id, |msg| {
1345                if let Some(att) = msg.attachments.last_mut() {
1346                    *att = adopted.clone();
1347                }
1348            });
1349            (r.key.clone(), r.nonce.clone(), r.url.clone(), r.size)
1350        }
1351        (None, body) => (params.key.clone(), params.nonce.clone(), String::new(), body.as_ref().map_or(0, |b| b.len())),
1352    };
1353
1354    // Upload to Blossom — bridge SendCallback.on_upload_progress to Blossom ProgressCallback
1355    let servers = crate::state::get_blossom_servers();
1356    let cb_for_progress = callback.clone();
1357    let pid_for_progress = pending_id.clone();
1358    let progress_cb: crate::blossom::ProgressCallback = Arc::new(move |percentage, bytes| {
1359        cb_for_progress.on_upload_progress(
1360            &pid_for_progress,
1361            percentage.unwrap_or(0),
1362            bytes.unwrap_or(0),
1363        )
1364    });
1365
1366    // Send the original MIME even though bytes are ciphertext: many
1367    // Blossom servers reject `application/octet-stream` but accept the
1368    // same bytes under their original type.
1369    let (upload_url, mirror_urls) = match encrypted {
1370        // Reuse: the attachment already points at a live blob. No upload, no
1371        // fan-out — the send is just the message.
1372        None => {
1373            callback.on_upload_complete(receiver_npub, &pending_id, &file_hash, &att_url);
1374            // A FOREIGN blob's lifetime belongs to its uploader; mirror it to
1375            // our servers in the background as availability insurance. Never
1376            // blocks or delays the send — best-effort by design.
1377            if reused.as_ref().is_some_and(|r| !r.mine) {
1378                let signer_bg = signer.clone();
1379                let url_bg = att_url.clone();
1380                crate::db::spawn_bound(async move {
1381                    let _ = crate::blossom::mirror_blob_to_servers(
1382                        signer_bg, &url_bg, crate::state::get_blossom_servers(),
1383                        1, std::time::Duration::from_secs(8), &[],
1384                    ).await;
1385                });
1386            }
1387            (att_url.clone(), Vec::new())
1388        }
1389        Some(encrypted) => {
1390            #[cfg_attr(target_arch = "wasm32", allow(unused_variables))]
1391            let body = encrypted.clone();
1392            let accepted = match crate::blossom::upload_body_with_progress_and_failover(
1393                signer.clone(), servers, encrypted, Some(mime_type),
1394                /* is_encrypted */ true,
1395                progress_cb, Some(config.upload_retries), Some(config.upload_retry_delay),
1396                cancel.clone(),
1397            ).await {
1398                Ok(accepted) => accepted,
1399                Err(e) => {
1400                    #[cfg(not(target_arch = "wasm32"))]
1401                    if !cancel.as_ref().is_some_and(|c| c.load(Ordering::Relaxed)) {
1402                        keep_for_retry(&body, ciphertext_file, &file_hash, &att_key, &att_nonce, &pending_id, mime_type);
1403                    }
1404                    return Err(mark_send_failed(&callback, receiver_npub, &pending_id, format!("Upload failed: {}", e)).await);
1405                }
1406            };
1407            // The account keeps media: the blob just uploaded is the copy it keeps.
1408            #[cfg(not(target_arch = "wasm32"))]
1409            if crate::media::keep_media() && keep_sent(&body, &file_hash, &att_key, &att_nonce, plain_len, mime_type) {
1410                let mut state = STATE.lock().await;
1411                state.update_message(&pending_id, |msg| {
1412                    if let Some(att) = msg.attachments.last_mut() {
1413                        att.set_downloaded(true);
1414                    }
1415                });
1416            }
1417
1418            let upload_url = accepted.url.clone();
1419            {
1420                let mut state = STATE.lock().await;
1421                state.update_message(&pending_id, |msg| {
1422                    if let Some(att) = msg.attachments.last_mut() {
1423                        att.url = upload_url.clone().into_boxed_str();
1424                    }
1425                });
1426            }
1427            callback.on_upload_complete(receiver_npub, &pending_id, &file_hash, &upload_url);
1428
1429            // BUD-04 mirror fan-out: bounded, best-effort. Verified mirrors ride the
1430            // rumor as NIP-17 `fallback` tags so the message survives its primary
1431            // host dying later; zero mirrors never delays or fails the send.
1432            let mirror_urls = crate::blossom::mirror_blob_to_servers(
1433                signer.clone(),
1434                &upload_url,
1435                crate::state::get_blossom_servers(),
1436                2,
1437                std::time::Duration::from_secs(5),
1438                std::slice::from_ref(&accepted.server),
1439            ).await;
1440            if !mirror_urls.is_empty() {
1441                let mut state = STATE.lock().await;
1442                state.update_message(&pending_id, |msg| {
1443                    if let Some(att) = msg.attachments.last_mut() {
1444                        att.set_fallback_urls(mirror_urls.iter().map(|s| s.as_str().into()));
1445                    }
1446                });
1447            }
1448            (upload_url, mirror_urls)
1449        }
1450    };
1451
1452    // A cancel during the mirror fan-out or the publish must not deliver: the
1453    // bubble is already gone on the sender's side.
1454    if cancel.as_ref().is_some_and(|c| c.load(Ordering::Relaxed)) {
1455        return Err("Upload cancelled".to_string());
1456    }
1457
1458    // Build Kind 15
1459    let mut file_rumor = EventBuilder::new(Kind::from_u16(15), &upload_url)
1460        .custom_created_at(Timestamp::from_secs(now.as_secs()))
1461        .tag(Tag::public_key(receiver))
1462        .tag(Tag::custom("file-type", [mime_type]))
1463        .tag(Tag::custom("size", [encrypted_size.to_string()]))
1464        .tag(Tag::custom("encryption-algorithm", ["aes-gcm"]))
1465        .tag(Tag::custom("decryption-key", [att_key.as_str()]))
1466        .tag(Tag::custom("decryption-nonce", [att_nonce.as_str()]))
1467        .tag(Tag::custom("ox", [file_hash.clone()]));
1468    if let Some(reply_id) = reply_to {
1469        file_rumor = file_rumor.tag(Tag::custom(
1470            "e",
1471            [reply_id.to_string(), String::new(), "reply".to_string()],
1472        ));
1473    }
1474    for fb in &mirror_urls {
1475        file_rumor = file_rumor.tag(Tag::custom("fallback", [fb.as_str()]));
1476    }
1477    if !filename.is_empty() {
1478        file_rumor = file_rumor.tag(Tag::custom("name", [filename]));
1479    }
1480    if let Some(ref topic) = webxdc_topic {
1481        file_rumor = file_rumor.tag(Tag::custom("webxdc-topic", [topic.as_str()]));
1482    }
1483    // Include image preview metadata for compatible rendering across all clients
1484    if let Some(ref meta) = img_meta {
1485        if !meta.thumbhash.is_empty() {
1486            // `thumbhash` names the value accurately; receivers read `thumb` too
1487            // (legacy), so this stays backward-compatible in both directions.
1488            file_rumor = file_rumor.tag(Tag::custom("thumbhash", [meta.thumbhash.as_str()]));
1489        }
1490        file_rumor = file_rumor.tag(Tag::custom("dim", [format!("{}x{}", meta.width, meta.height)]));
1491    }
1492    file_rumor = file_rumor.tag(Tag::custom("ms", [milliseconds.to_string()]));
1493    // The self-destruct clock starts at publish: resolve the lifespan now that the
1494    // upload is done, and put the same stamp on the sender's own bubble.
1495    let expiration = config
1496        .self_destruct_secs
1497        .and_then(crate::self_destruct::expiry_after)
1498        .or(config.expiration);
1499    if let Some(exp) = expiration {
1500        file_rumor = file_rumor.tag(Tag::expiration(Timestamp::from_secs(exp)));
1501        let mut state = STATE.lock().await;
1502        state.update_message(&pending_id, |msg| { msg.expiration_secs = exp as u32; });
1503    }
1504
1505    let built_rumor = file_rumor.finalize_unsigned_with_id(my_pk);
1506    let event_id = built_rumor.id.ok_or("Rumor has no id")?.to_hex();
1507
1508    retry_send_gift_wrap(
1509        &client, &receiver, receiver_npub, &pending_id,
1510        built_rumor, &event_id, config, callback, None,
1511    ).await
1512}
1513
1514// ============================================================================
1515// Tests
1516// ============================================================================
1517
1518#[cfg(test)]
1519mod tests {
1520    use super::*;
1521    use std::sync::Mutex;
1522
1523    #[derive(Debug, Clone, PartialEq)]
1524    enum CbEvent {
1525        Pending(String),
1526        UploadProgress(String, u8, u64),
1527        UploadComplete(String, String),
1528        Sent(String, String),
1529        Failed(String, String),
1530        Persist(String),
1531    }
1532
1533    struct MockCallback {
1534        events: Mutex<Vec<CbEvent>>,
1535        cancel_at: Option<u8>,
1536    }
1537
1538    impl MockCallback {
1539        fn new() -> Self { Self { events: Mutex::new(vec![]), cancel_at: None } }
1540        fn with_cancel(pct: u8) -> Self { Self { events: Mutex::new(vec![]), cancel_at: Some(pct) } }
1541        fn events(&self) -> Vec<CbEvent> { self.events.lock().unwrap().clone() }
1542    }
1543
1544    impl SendCallback for MockCallback {
1545        fn on_pending(&self, cid: &str, _: &Message) {
1546            self.events.lock().unwrap().push(CbEvent::Pending(cid.into()));
1547        }
1548        fn on_upload_progress(&self, pid: &str, pct: u8, bytes: u64) -> Result<(), String> {
1549            self.events.lock().unwrap().push(CbEvent::UploadProgress(pid.into(), pct, bytes));
1550            if self.cancel_at.map_or(false, |c| pct >= c) { return Err("Cancelled".into()); }
1551            Ok(())
1552        }
1553        fn on_upload_complete(&self, cid: &str, _: &str, _: &str, url: &str) {
1554            self.events.lock().unwrap().push(CbEvent::UploadComplete(cid.into(), url.into()));
1555        }
1556        fn on_sent(&self, cid: &str, old: &str, _: &Message) {
1557            self.events.lock().unwrap().push(CbEvent::Sent(cid.into(), old.into()));
1558        }
1559        fn on_failed(&self, cid: &str, old: &str, _: &Message) {
1560            self.events.lock().unwrap().push(CbEvent::Failed(cid.into(), old.into()));
1561        }
1562        fn on_persist(&self, cid: &str, _: &Message) {
1563            self.events.lock().unwrap().push(CbEvent::Persist(cid.into()));
1564        }
1565    }
1566
1567    #[test]
1568    fn config_default() {
1569        let c = SendConfig::default();
1570        assert_eq!(c.max_send_attempts, 1);
1571        assert!(!c.self_send);
1572        assert!(c.cancel_token.is_none());
1573        assert_eq!(c.upload_retries, 3);
1574    }
1575
1576    #[test]
1577    fn config_gui() {
1578        let c = SendConfig::gui();
1579        assert_eq!(c.max_send_attempts, 12);
1580        assert!(c.self_send);
1581    }
1582
1583    #[test]
1584    fn config_headless() {
1585        let c = SendConfig::headless();
1586        assert_eq!(c.max_send_attempts, 3);
1587        assert!(c.self_send);
1588    }
1589
1590    #[test]
1591    fn config_custom_override() {
1592        let c = SendConfig { max_send_attempts: 5, ..SendConfig::gui() };
1593        assert_eq!(c.max_send_attempts, 5);
1594        assert!(c.self_send);
1595    }
1596
1597    #[test]
1598    fn noop_callback_all_methods() {
1599        let cb = NoOpSendCallback;
1600        let msg = Message::default();
1601        cb.on_pending("c", &msg);
1602
1603        assert!(cb.on_upload_progress("p", 50, 1024).is_ok());
1604        cb.on_upload_complete("c", "p", "a", "url");
1605        cb.on_sent("c", "o", &msg);
1606        cb.on_failed("c", "o", &msg);
1607        cb.on_persist("c", &msg);
1608    }
1609
1610    #[test]
1611    fn text_dm_sequence() {
1612        let cb = MockCallback::new();
1613        let msg = Message::default();
1614        cb.on_pending("r", &msg);
1615        cb.on_sent("r", "p-1", &msg);
1616        cb.on_persist("r", &msg);
1617        assert_eq!(cb.events(), vec![
1618            CbEvent::Pending("r".into()),
1619            CbEvent::Sent("r".into(), "p-1".into()),
1620            CbEvent::Persist("r".into()),
1621        ]);
1622    }
1623
1624    #[test]
1625    fn file_dm_sequence() {
1626        let cb = MockCallback::new();
1627        let msg = Message::default();
1628        cb.on_pending("r", &msg);
1629
1630        cb.on_upload_progress("p", 0, 0).ok();
1631        cb.on_upload_progress("p", 50, 5000).ok();
1632        cb.on_upload_progress("p", 100, 10000).ok();
1633        cb.on_upload_complete("r", "p", "h", "https://blossom/h");
1634        cb.on_sent("r", "p", &msg);
1635        cb.on_persist("r", &msg);
1636        let e = cb.events();
1637        assert_eq!(e.len(), 7);
1638        assert!(matches!(&e[4], CbEvent::UploadComplete(_, url) if url.contains("blossom")));
1639    }
1640
1641    #[test]
1642    fn failed_sequence() {
1643        let cb = MockCallback::new();
1644        let msg = Message::default();
1645        cb.on_pending("r", &msg);
1646        cb.on_failed("r", "p", &msg);
1647        cb.on_persist("r", &msg);
1648        assert_eq!(cb.events(), vec![
1649            CbEvent::Pending("r".into()),
1650            CbEvent::Failed("r".into(), "p".into()),
1651            CbEvent::Persist("r".into()),
1652        ]);
1653    }
1654
1655    #[test]
1656    fn cancel_upload_at_threshold() {
1657        let cb = MockCallback::with_cancel(50);
1658        assert!(cb.on_upload_progress("p", 25, 512).is_ok());
1659        assert!(cb.on_upload_progress("p", 50, 1024).is_err());
1660        assert_eq!(cb.events().len(), 2);
1661    }
1662
1663    #[test]
1664    fn cancel_triggers_failed() {
1665        let cb = MockCallback::with_cancel(30);
1666        let msg = Message::default();
1667        cb.on_pending("r", &msg);
1668
1669        cb.on_upload_progress("p", 10, 1000).ok();
1670        assert!(cb.on_upload_progress("p", 30, 3000).is_err());
1671        cb.on_failed("r", "p", &msg);
1672        assert!(matches!(cb.events().last(), Some(CbEvent::Failed(..))));
1673    }
1674
1675    #[test]
1676    fn send_result_serialize() {
1677        let r = SendResult { pending_id: "p".into(), event_id: Some("e".into()), chat_id: "c".into() };
1678        let j = serde_json::to_string(&r).unwrap();
1679        assert!(j.contains("\"pending_id\":\"p\""));
1680    }
1681
1682    #[test]
1683    fn send_result_none_event() {
1684        let r = SendResult { pending_id: "p".into(), event_id: None, chat_id: "c".into() };
1685        let j = serde_json::to_string(&r).unwrap();
1686        assert!(j.contains("null"));
1687    }
1688
1689    // ========================================================================
1690    // File DM callback sequences
1691    // ========================================================================
1692
1693    #[test]
1694    fn file_dm_fresh_upload_full_sequence() {
1695        let cb = MockCallback::new();
1696        let msg = Message::default();
1697
1698        // 1. Pending message created
1699        cb.on_pending("npub1recv", &msg);
1700        // 2. Attachment preview added
1701
1702        // 3. Upload progress (0% → 25% → 50% → 75% → 100%)
1703        cb.on_upload_progress("pending-42", 0, 0).unwrap();
1704        cb.on_upload_progress("pending-42", 25, 2500).unwrap();
1705        cb.on_upload_progress("pending-42", 50, 5000).unwrap();
1706        cb.on_upload_progress("pending-42", 75, 7500).unwrap();
1707        cb.on_upload_progress("pending-42", 100, 10000).unwrap();
1708        // 4. Upload complete
1709        cb.on_upload_complete("npub1recv", "pending-42", "deadbeef", "https://blossom.example/deadbeef");
1710        // 5. Gift-wrap sent successfully
1711        cb.on_sent("npub1recv", "pending-42", &msg);
1712        // 6. Persisted to DB
1713        cb.on_persist("npub1recv", &msg);
1714
1715        let e = cb.events();
1716        assert_eq!(e.len(), 9);
1717        assert!(matches!(&e[0], CbEvent::Pending(c) if c == "npub1recv"));
1718        assert!(matches!(&e[1], CbEvent::UploadProgress(_, 0, 0)));
1719        assert!(matches!(&e[5], CbEvent::UploadProgress(_, 100, 10000)));
1720        assert!(matches!(&e[6], CbEvent::UploadComplete(_, url) if url.contains("deadbeef")));
1721        assert!(matches!(&e[7], CbEvent::Sent(..)));
1722        assert!(matches!(&e[8], CbEvent::Persist(..)));
1723    }
1724
1725    #[test]
1726    fn file_dm_skip_upload_sequence() {
1727        let cb = MockCallback::new();
1728        let msg = Message::default();
1729
1730        // Dedup hit: no upload, existing URL reused
1731        // 1. Pending message
1732        cb.on_pending("npub1recv", &msg);
1733        // 2. Attachment preview (with reused URL already set)
1734
1735        // 3. Upload complete (immediate — URL was already known)
1736        cb.on_upload_complete("npub1recv", "pending-99", "existinghash", "https://blossom.example/existing");
1737        // 4. Gift-wrap sent
1738        cb.on_sent("npub1recv", "pending-99", &msg);
1739        // 5. Persisted
1740        cb.on_persist("npub1recv", &msg);
1741
1742        let e = cb.events();
1743        assert_eq!(e.len(), 4);
1744        // No UploadProgress events — upload was skipped
1745        assert!(!e.iter().any(|ev| matches!(ev, CbEvent::UploadProgress(..))));
1746        assert!(matches!(&e[1], CbEvent::UploadComplete(..)));
1747    }
1748
1749    #[test]
1750    fn file_dm_upload_cancelled_at_30pct() {
1751        let cb = MockCallback::with_cancel(30);
1752        let msg = Message::default();
1753
1754        cb.on_pending("npub1recv", &msg);
1755
1756        assert!(cb.on_upload_progress("p", 10, 1000).is_ok());
1757        assert!(cb.on_upload_progress("p", 20, 2000).is_ok());
1758        // Cancel triggers at 30%
1759        let err = cb.on_upload_progress("p", 30, 3000);
1760        assert!(err.is_err());
1761        assert!(err.unwrap_err().contains("Cancelled"));
1762        // Pipeline marks as failed
1763        cb.on_failed("npub1recv", "p", &msg);
1764
1765        let e = cb.events();
1766        assert_eq!(e.len(), 5);
1767        // No Sent, no Persist after cancel — just Failed
1768        assert!(!e.iter().any(|ev| matches!(ev, CbEvent::Sent(..))));
1769        assert!(matches!(e.last(), Some(CbEvent::Failed(..))));
1770    }
1771
1772    #[test]
1773    fn file_dm_upload_fails_marks_failed() {
1774        let cb = MockCallback::new();
1775        let msg = Message::default();
1776
1777        cb.on_pending("npub1recv", &msg);
1778
1779        cb.on_upload_progress("p", 0, 0).ok();
1780        cb.on_upload_progress("p", 10, 500).ok();
1781        // Upload fails (server error, all retries exhausted)
1782        cb.on_failed("npub1recv", "p", &msg);
1783        cb.on_persist("npub1recv", &msg);
1784
1785        let e = cb.events();
1786        assert_eq!(e.len(), 5);
1787        assert!(matches!(&e[3], CbEvent::Failed(..)));
1788        assert!(matches!(&e[4], CbEvent::Persist(..)));
1789        // No UploadComplete, no Sent
1790        assert!(!e.iter().any(|ev| matches!(ev, CbEvent::UploadComplete(..))));
1791        assert!(!e.iter().any(|ev| matches!(ev, CbEvent::Sent(..))));
1792    }
1793
1794    #[test]
1795    fn file_dm_gift_wrap_fails_after_upload() {
1796        let cb = MockCallback::new();
1797        let msg = Message::default();
1798
1799        // Upload succeeds but gift-wrap fails
1800        cb.on_pending("npub1recv", &msg);
1801
1802        cb.on_upload_progress("p", 100, 10000).ok();
1803        cb.on_upload_complete("npub1recv", "p", "hash", "https://blossom/hash");
1804        // Gift-wrap retry exhausted
1805        cb.on_failed("npub1recv", "p", &msg);
1806        cb.on_persist("npub1recv", &msg);
1807
1808        let e = cb.events();
1809        assert_eq!(e.len(), 5);
1810        // Upload succeeded but send failed
1811        assert!(matches!(&e[2], CbEvent::UploadComplete(..)));
1812        assert!(matches!(&e[3], CbEvent::Failed(..)));
1813    }
1814
1815    #[test]
1816    fn file_dm_with_image_metadata_sequence() {
1817        let cb = MockCallback::new();
1818        let msg = Message::default();
1819
1820        // Image with thumbhash + dimensions
1821        cb.on_pending("npub1recv", &msg);
1822
1823        cb.on_upload_progress("p", 0, 0).ok();
1824        cb.on_upload_progress("p", 50, 50000).ok();
1825        cb.on_upload_progress("p", 100, 100000).ok();
1826        cb.on_upload_complete("npub1recv", "p", "imghash", "https://blossom/imghash.jpg");
1827        cb.on_sent("npub1recv", "p", &msg);
1828        cb.on_persist("npub1recv", &msg);
1829
1830        let e = cb.events();
1831        assert_eq!(e.len(), 7);
1832        // Verify ordering: pending → progress(3x) → complete → sent → persist
1833        assert!(matches!(&e[0], CbEvent::Pending(..)));
1834        assert!(matches!(&e[4], CbEvent::UploadComplete(_, url) if url.ends_with(".jpg")));
1835        assert!(matches!(&e[5], CbEvent::Sent(..)));
1836    }
1837
1838    #[test]
1839    fn cancel_token_config_with_upload() {
1840        let token = Arc::new(std::sync::atomic::AtomicBool::new(false));
1841        let c = SendConfig {
1842            cancel_token: Some(token.clone()),
1843            ..SendConfig::gui()
1844        };
1845        assert!(c.cancel_token.is_some());
1846        assert!(!token.load(std::sync::atomic::Ordering::Relaxed));
1847
1848        // Simulate cancel
1849        token.store(true, std::sync::atomic::Ordering::Relaxed);
1850        assert!(c.cancel_token.as_ref().unwrap().load(std::sync::atomic::Ordering::Relaxed));
1851    }
1852}
1853
1854#[cfg(test)]
1855mod seal_tests {
1856    use super::*;
1857    use std::sync::Mutex;
1858
1859    #[derive(Default)]
1860    struct Stages(Mutex<Vec<(String, Option<u8>)>>);
1861    impl SendCallback for Stages {
1862        fn on_upload_stage(&self, _: &str, stage: &str, pct: Option<u8>) {
1863            self.0.lock().unwrap().push((stage.to_string(), pct));
1864        }
1865    }
1866
1867    #[tokio::test]
1868    async fn bytes_and_files_seal_to_what_their_key_opens() {
1869        let plain: Vec<u8> = (0..300_000u32).map(|i| (i * 7 % 251) as u8).collect();
1870        let params = crypto::generate_encryption_params();
1871        let hash = crypto::sha256_hex(&plain);
1872        let src = std::env::temp_dir().join(format!("vector-seal-{}.bin", std::process::id()));
1873        std::fs::write(&src, &plain).unwrap();
1874
1875        for source in [FileSource::Bytes(Arc::new(plain.clone())), FileSource::Path(src.clone())] {
1876            let from_file = matches!(source, FileSource::Path(_));
1877            let stages = Arc::new(Stages::default());
1878            let sealed = seal_or_reuse(source, &hash, &params.key, &params.nonce, "pending-1", stages.clone(), None).await.unwrap();
1879            let Sealed::Body(body, guard) = sealed else { panic!("nothing to reuse without a database") };
1880            let ciphertext = match &body {
1881                crate::blossom::UploadBody::Memory(b) => b.to_vec(),
1882                crate::blossom::UploadBody::File { path, .. } => std::fs::read(path).unwrap(),
1883            };
1884            assert_eq!(body.len(), plain.len() as u64 + 16);
1885            assert_eq!(crypto::decrypt_data(&ciphertext, &params.key, &params.nonce).unwrap(), plain);
1886            let stages = stages.0.lock().unwrap().clone();
1887            assert_eq!(stages.first().unwrap().0, "encrypting");
1888            assert_eq!(stages.last().unwrap(), &("starting".to_string(), None));
1889            assert_eq!(guard.is_some(), from_file);
1890            if let crate::blossom::UploadBody::File { path, .. } = &body {
1891                drop(guard);
1892                assert!(!path.exists(), "the ciphertext goes with its guard");
1893            }
1894        }
1895        let _ = std::fs::remove_file(&src);
1896    }
1897
1898    #[tokio::test]
1899    async fn an_upload_shows_the_bytes_in_hand_while_it_goes() {
1900        struct Shown(Mutex<Option<Message>>);
1901        impl SendCallback for Shown {
1902            fn on_pending(&self, _: &str, msg: &Message) {
1903                *self.0.lock().unwrap() = Some(msg.clone());
1904            }
1905        }
1906        let session = crate::db::Session::empty();
1907        let me = Keys::generate();
1908        let file = std::env::temp_dir().join(format!("vector-shown-{}.bin", std::process::id()));
1909        std::fs::write(&file, vec![7u8; 4096]).unwrap();
1910        let shown = Arc::new(Shown(Mutex::new(None)));
1911        crate::db::with_session(session, async {
1912            crate::state::set_nostr_client(crate::nostr_client_builder().build());
1913            crate::state::set_my_public_key(me.public_key());
1914            crate::signer::set_test_signer(Some(crate::signer::ActiveSigner::Keys(me.clone())));
1915            // Called off before its seal: nothing reaches a server.
1916            let config = SendConfig { cancel_token: Some(Arc::new(AtomicBool::new(true))), ..SendConfig::default() };
1917            let to = Keys::generate().public_key().to_bech32().unwrap();
1918            let sent = send_file_dm_from(&to, FileSource::Path(file.clone()), "a.bin", "bin", None, None, None, &config, shown.clone()).await;
1919            crate::signer::set_test_signer(None);
1920            assert!(sent.is_err(), "the cancelled send ends failed");
1921        })
1922        .await;
1923        let _ = std::fs::remove_file(&file);
1924        let msg = shown.0.lock().unwrap().clone().expect("the bubble went up");
1925        let att = &msg.attachments[0];
1926        assert!(!att.downloaded && att.path.is_empty(), "the sender keeps no copy of its own");
1927        assert!(att.resident, "the bubble draws the bytes it's sending, rather than offering to download them");
1928    }
1929
1930    #[tokio::test]
1931    async fn a_pending_wrap_confirm_does_not_keep_its_account_alive() {
1932        let session = crate::db::Session::empty();
1933        struct NoCallback;
1934        impl SendCallback for NoCallback {}
1935        let rumor = EventBuilder::new(Kind::PrivateDirectMessage, "hi").finalize_unsigned_with_id(Keys::generate().public_key());
1936        crate::db::with_session(session.clone(), async {
1937            register_wrap_confirm(Arc::new(WrapConfirm {
1938                wrap_id: EventId::from_byte_array([0; 32]),
1939                chat_id: String::new(),
1940                pending_id: String::new(),
1941                rumor_event_id: String::new(),
1942                rumor,
1943                callback: Arc::new(NoCallback),
1944                self_send: false,
1945                confirmed: AtomicBool::new(false),
1946                rescued: AtomicBool::new(false),
1947                loop_exited: AtomicBool::new(true),
1948                notify: tokio::sync::Notify::new(),
1949                session: Arc::downgrade(&crate::db::current_session()),
1950                registered_at: web_time::Instant::now(),
1951            }));
1952            assert_eq!(wrap_confirms().lock().unwrap().len(), 1, "registered on this session");
1953        })
1954        .await;
1955        assert_eq!(Arc::strong_count(&session), 1, "the registry's entry holds no strong reference");
1956        let weak = Arc::downgrade(&session);
1957        drop(session);
1958        assert!(weak.upgrade().is_none(), "the account is freed once nothing else holds it");
1959    }
1960}