vector-core 0.2.0

Core library for Vector — the single source of truth for all Vector clients, SDKs, and interfaces.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
//! Message sending — NIP-17 gift-wrapped DMs (text and file attachments).
//!
//! This is the core send pipeline used by all Vector interfaces (GUI, CLI, SDK).
//! Clients provide a `SendCallback` for status notifications (pending/sent/failed/progress)
//! and a `SendConfig` for retry/cancel behavior.

use std::sync::Arc;
use std::sync::atomic::AtomicBool;
use nostr_sdk::prelude::*;

use crate::state::{nostr_client, my_public_key, STATE};
use crate::types::{Message, Attachment};
use crate::crypto;

// ============================================================================
// SendCallback — Client notification trait
// ============================================================================

/// Callbacks invoked during the DM send pipeline.
///
/// Each method has a default no-op so simple callers (CLI, bots, tests)
/// implement only what they need. Methods are synchronous and non-fallible
/// by design — they should never block the send pipeline.
///
/// Exception: `on_upload_progress` returns `Result` — return `Err` to cancel.
pub trait SendCallback: Send + Sync {
    /// Message created and added to STATE as pending.
    fn on_pending(&self, _chat_id: &str, _msg: &Message) {}

    /// File upload progress. Return Err("...") to cancel the upload.
    fn on_upload_progress(
        &self,
        _pending_id: &str,
        _percentage: u8,
        _bytes_sent: u64,
    ) -> Result<(), String> {
        Ok(())
    }

    /// Upload complete, attachment URL now available.
    fn on_upload_complete(&self, _chat_id: &str, _pending_id: &str, _attachment_id: &str, _url: &str) {}

    /// Message successfully delivered to at least one relay.
    /// `old_id` is the pending ID, `msg` has the real event ID.
    fn on_sent(&self, _chat_id: &str, _old_id: &str, _msg: &Message) {}

    /// Message delivery failed after all retry attempts.
    fn on_failed(&self, _chat_id: &str, _old_id: &str, _msg: &Message) {}

    /// Persist message to database. Default is no-op.
    /// Tauri implements this to call save_message + save_slim_chat.
    fn on_persist(&self, _chat_id: &str, _msg: &Message) {}
}

/// No-op callback for headless/CLI/test use.
pub struct NoOpSendCallback;
impl SendCallback for NoOpSendCallback {}

// ============================================================================
// SendConfig — Per-call configuration
// ============================================================================

/// Configuration for a send operation.
pub struct SendConfig {
    /// Max gift-wrap send attempts (default: 1).
    pub max_send_attempts: u32,
    /// Delay between send retries (default: 5 seconds).
    pub retry_delay: std::time::Duration,
    /// Send copy to own inbox for recovery/sync (default: false).
    pub self_send: bool,
    /// Cancel token for file uploads — set to true to abort.
    pub cancel_token: Option<Arc<AtomicBool>>,
    /// Max Blossom upload retries per server (default: 3).
    pub upload_retries: u32,
    /// Delay between upload retries (default: 2 seconds).
    pub upload_retry_delay: std::time::Duration,
}

impl Default for SendConfig {
    fn default() -> Self {
        Self {
            max_send_attempts: 1,
            retry_delay: std::time::Duration::from_secs(5),
            self_send: false,
            cancel_token: None,
            upload_retries: 3,
            upload_retry_delay: std::time::Duration::from_secs(2),
        }
    }
}

impl SendConfig {
    /// Preset for GUI clients (12 retries, self-send enabled).
    pub fn gui() -> Self {
        Self {
            max_send_attempts: 12,
            self_send: true,
            ..Default::default()
        }
    }

    /// Preset for headless/background mode (3 retries, self-send enabled).
    pub fn headless() -> Self {
        Self {
            max_send_attempts: 3,
            self_send: true,
            ..Default::default()
        }
    }
}

// ============================================================================
// SendResult
// ============================================================================

/// Result of sending a message.
#[derive(serde::Serialize, Clone, Debug)]
pub struct SendResult {
    /// The pending ID used while sending
    pub pending_id: String,
    /// The real event ID after successful send (None if failed)
    pub event_id: Option<String>,
    /// The chat ID (receiver npub for DMs)
    pub chat_id: String,
}

// ============================================================================
// Internal: retry gift-wrap send
// ============================================================================

/// Shared tail of send_dm / send_file_dm / send_rumor_dm:
/// gift-wrap → retry loop → finalize/fail → self-send.
///
/// Each successful wrap is persisted via `db::nip17_keys::store_wrap_key`
/// so that the user can later issue a NIP-09 deletion against the
/// kind-1059 wrap event id. Recipient wrap and self-send wrap each
/// retain their own ephemeral key.
async fn retry_send_gift_wrap(
    client: &Client,
    receiver: &PublicKey,
    receiver_npub: &str,
    pending_id: &str,
    rumor: UnsignedEvent,
    event_id: &str,
    config: &SendConfig,
    callback: Arc<dyn SendCallback>,
) -> Result<SendResult, String> {
    let my_pk = my_public_key().ok_or("Public key not set")?;
    let inner_rumor_id = rumor.id;

    for attempt in 0..config.max_send_attempts {
        match crate::inbox_relays::send_gift_wrap_retained(client, receiver, rumor.clone(), []).await {
            Ok(outcome) if outcome.output.success.is_empty() => {
                // The publish round-trip succeeded but every targeted relay
                // rejected the wrap (auth required, kind filter, rate-limit,
                // timed-out OK, etc.). Surface the per-relay failure reasons
                // so the user can see WHY their DMs aren't being accepted.
                let failures: Vec<String> = outcome.output.failed.iter()
                    .map(|(url, err)| format!("{}: {}", url, err))
                    .collect();
                let targeted_count = outcome.targeted_relays.len();
                crate::log_warn!(
                    "[Send] attempt {}/{} — 0 of {} relays accepted (targeted: {}). Per-relay errors: {}",
                    attempt + 1,
                    config.max_send_attempts,
                    targeted_count,
                    outcome.targeted_relays.join(", "),
                    if failures.is_empty() {
                        "(none reported — likely all timed out before responding)".to_string()
                    } else {
                        failures.join(" | ")
                    },
                );
                if attempt + 1 >= config.max_send_attempts {
                    // All attempts exhausted — mark failed
                    let failed_msg = {
                        let mut state = STATE.lock().await;
                        state.update_message(pending_id, |msg| {
                            msg.set_failed(true);
                            msg.set_pending(false);
                        })
                    };
                    if let Some((_chat_id, ref msg)) = failed_msg {
                        callback.on_failed(receiver_npub, pending_id, msg);
                        callback.on_persist(receiver_npub, msg);
                    }
                    return Err(format!("Failed to send DM after {} attempts (no relays accepted the gift-wrap)", config.max_send_attempts));
                }
                tokio::time::sleep(config.retry_delay).await;
                continue;
            }
            Ok(outcome) => {
                // At least one relay accepted — success.
                // Persist the retained ephemeral key so the user can
                // later issue NIP-09 deletion against this wrap.
                if let Some(rid) = inner_rumor_id {
                    let role = if attempt == 0 {
                        crate::db::nip17_keys::WrapRole::Recipient
                    } else {
                        crate::db::nip17_keys::WrapRole::Retry
                    };
                    if let Err(e) = crate::db::nip17_keys::store_wrap_key(
                        &outcome.wrap_event_id,
                        &rid,
                        receiver,
                        role,
                        &outcome.wrap_secret,
                        &outcome.targeted_relays,
                    ) {
                        eprintln!("[NIP-17] failed to persist wrap key: {}", e);
                    }
                }

                let finalized = {
                    let mut state = STATE.lock().await;
                    state.finalize_pending_message(receiver_npub, pending_id, event_id)
                };

                if let Some((_old_id, ref finalized_msg)) = finalized {
                    callback.on_sent(receiver_npub, pending_id, finalized_msg);
                    callback.on_persist(receiver_npub, finalized_msg);
                }

                // Self-send for recovery + retain wrap key so the user
                // can later delete their own copy from inbox relays.
                // SessionGuard skips publish + DB write on swap; without
                // it account A's wrap key would corrupt account B's
                // nip17_keys delete-history.
                if config.self_send {
                    let client = client.clone();
                    let my_pk_clone = my_pk;
                    let rumor_clone = rumor.clone();
                    let rid_for_self = inner_rumor_id;
                    let session = crate::state::SessionGuard::capture();
                    tokio::spawn(async move {
                        if !session.is_valid() { return; }
                        match crate::inbox_relays::send_gift_wrap_retained(
                            &client, &my_pk_clone, rumor_clone, [],
                        ).await {
                            Ok(self_outcome) if !self_outcome.output.success.is_empty() => {
                                if !session.is_valid() { return; }
                                if let Some(rid) = rid_for_self {
                                    if let Err(e) = crate::db::nip17_keys::store_wrap_key(
                                        &self_outcome.wrap_event_id,
                                        &rid,
                                        &my_pk_clone,
                                        crate::db::nip17_keys::WrapRole::SelfSend,
                                        &self_outcome.wrap_secret,
                                        &self_outcome.targeted_relays,
                                    ) {
                                        eprintln!("[NIP-17] failed to persist self-wrap key: {}", e);
                                    }
                                }
                            }
                            _ => {}
                        }
                    });
                }

                return Ok(SendResult {
                    pending_id: pending_id.to_string(),
                    event_id: Some(event_id.to_string()),
                    chat_id: receiver_npub.to_string(),
                });
            }
            Err(e) => {
                // send_gift_wrap_retained itself errored before even
                // attempting a publish (seal/wrap failure, signer issue,
                // pool resolution problem). Log so we can tell this apart
                // from "publishes ran but all relays rejected".
                crate::log_warn!(
                    "[Send] attempt {}/{} — send_gift_wrap_retained errored: {}",
                    attempt + 1,
                    config.max_send_attempts,
                    e,
                );
                if attempt + 1 >= config.max_send_attempts {
                    let failed_msg = {
                        let mut state = STATE.lock().await;
                        state.update_message(pending_id, |msg| {
                            msg.set_failed(true);
                            msg.set_pending(false);
                        })
                    };
                    if let Some((_chat_id, ref msg)) = failed_msg {
                        callback.on_failed(receiver_npub, pending_id, msg);
                        callback.on_persist(receiver_npub, msg);
                    }
                    return Err(format!("Failed to send DM after {} attempts: {}", config.max_send_attempts, e));
                }
                tokio::time::sleep(config.retry_delay).await;
            }
        }
    }

    Err("Send loop exited unexpectedly".to_string())
}

// ============================================================================
// send_dm — Text DMs
// ============================================================================

/// Send a NIP-17 gift-wrapped text DM.
///
/// Flow: pending msg → callback.on_pending → build Kind 14 rumor →
/// gift-wrap with retry → finalize → callback.on_sent → optional self-send.
pub async fn send_dm(
    receiver_npub: &str,
    content: &str,
    reply_to: Option<&str>,
    config: &SendConfig,
    callback: Arc<dyn SendCallback>,
) -> Result<SendResult, String> {
    let client = nostr_client().ok_or("Not logged in")?;
    let my_pk = my_public_key().ok_or("Public key not set")?;

    let now = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH).unwrap();
    let pending_id = format!("pending-{}", now.as_nanos());

    let receiver = PublicKey::from_bech32(receiver_npub)
        .map_err(|e| format!("Invalid npub: {}", e))?;

    // NIP-30: resolve any `:shortcode:` in the outbound text against the
    // user's subscribed packs so the rumor carries `["emoji", ...]` tags.
    // Recipients without the pack subscribed still render correctly, and
    // our own-view echo populates `emoji_tags` for the renderer.
    let emoji_tags = crate::emoji_packs::resolve_outbound_emoji_tags(content);

    // Build pending message and add to state
    let msg = Message {
        id: pending_id.clone(),
        content: content.to_string(),
        replied_to: reply_to.unwrap_or("").to_string(),
        at: now.as_millis() as u64,
        pending: true,
        mine: true,
        npub: my_pk.to_bech32().ok(),
        emoji_tags: emoji_tags.clone(),
        ..Default::default()
    };

    {
        let mut state = STATE.lock().await;
        state.add_message_to_participant(receiver_npub, msg.clone());
    }

    callback.on_pending(receiver_npub, &msg);

    // Build the rumor
    let milliseconds = now.as_millis() % 1000;
    let mut rumor = EventBuilder::private_msg_rumor(receiver, content);

    if let Some(reply_id) = reply_to {
        if !reply_id.is_empty() {
            rumor = rumor.tag(Tag::custom(
                TagKind::e(),
                [reply_id.to_string(), String::new(), "reply".to_string()],
            ));
        }
    }

    let mut rumor = rumor.tag(Tag::custom(TagKind::custom("ms"), [milliseconds.to_string()]));
    for et in &emoji_tags {
        rumor = rumor.tag(Tag::custom(
            TagKind::custom("emoji"),
            [et.shortcode.clone(), et.url.clone()],
        ));
    }
    let built_rumor = rumor.build(my_pk);
    let event_id = built_rumor.id.ok_or("Rumor has no id")?.to_hex();

    // Send via gift-wrap with retry
    retry_send_gift_wrap(
        &client, &receiver, receiver_npub, &pending_id,
        built_rumor, &event_id, config, callback,
    ).await
}

// ============================================================================
// send_rumor_dm — Pre-built rumor (custom events)
// ============================================================================

/// Send a pre-built rumor via NIP-17 gift-wrap.
///
/// Used when the caller has already built the rumor. Skips encryption/upload.
pub async fn send_rumor_dm(
    receiver_npub: &str,
    pending_id: &str,
    rumor: UnsignedEvent,
    config: &SendConfig,
    callback: Arc<dyn SendCallback>,
) -> Result<SendResult, String> {
    let client = nostr_client().ok_or("Not logged in")?;

    let receiver = PublicKey::from_bech32(receiver_npub)
        .map_err(|e| format!("Invalid npub: {}", e))?;

    let event_id = rumor.id.ok_or("Rumor has no id")?.to_hex();

    retry_send_gift_wrap(
        &client, &receiver, receiver_npub, pending_id,
        rumor, &event_id, config, callback,
    ).await
}

// ============================================================================
// send_file_dm — File Attachment DMs
// ============================================================================

/// Send a NIP-17 gift-wrapped file attachment DM.
///
/// Flow: hash → save locally → encrypt → upload → build Kind 15 rumor → gift-wrap + send.
pub async fn send_file_dm(
    receiver_npub: &str,
    file_bytes: Arc<Vec<u8>>,
    filename: &str,
    extension: &str,
    content: Option<&str>,
    config: &SendConfig,
    callback: Arc<dyn SendCallback>,
) -> Result<SendResult, String> {
    let client = nostr_client().ok_or("Not logged in")?;
    let my_pk = my_public_key().ok_or("Public key not set")?;
    // Sign the Blossom auth event via the active client signer so bunker
    // accounts route through NostrConnect (the user's identity key lives on
    // the remote signer; MY_SECRET_KEY only holds the NIP-46 client key).
    let signer = client.signer().await
        .map_err(|e| format!("Signer unavailable: {}", e))?;

    let now = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH).unwrap();
    let pending_id = format!("pending-{}", now.as_nanos());
    let milliseconds = now.as_millis() % 1000;

    let receiver = PublicKey::from_bech32(receiver_npub)
        .map_err(|e| format!("Invalid npub: {}", e))?;

    let file_hash = crypto::sha256_hex(&file_bytes);
    let mime_type = crypto::mime_from_extension(extension);

    // WebXDC Mini Apps: mint the realtime-channel topic at send time and carry
    // it on the rumor — locally-derived topics are asymmetric in DMs (each
    // side's chat_id is the other party's npub), splitting players onto
    // disjoint gossip topics.
    let webxdc_topic = (extension.eq_ignore_ascii_case("xdc"))
        .then(|| crate::webxdc::mint_topic_id(&file_hash, &my_pk.to_hex()));

    // Save file locally so the attachment is immediately viewable
    let download_dir = crate::db::get_download_dir();
    let _ = std::fs::create_dir_all(&download_dir);
    // Save with an extension matching the actual content. The caller's
    // `extension` argument is post-compression (e.g. JPEG when an
    // original PNG was compressed), but `filename` is the user-facing
    // name which may still carry the pre-compression extension. If we
    // honored `filename` verbatim we'd save JPEG bytes as `.png` and
    // poison any future re-upload with a MIP-04 mismatch.
    let local_name = if filename.is_empty() {
        format!("{}.{}", &file_hash, extension)
    } else {
        let stem = filename.rsplit_once('.').map(|(s, _)| s).unwrap_or(filename);
        format!("{}.{}", stem, extension)
    };
    // Resolve unique path (pasted_image.png → pasted_image-1.png on collision)
    let local_path = crypto::resolve_unique_filename(&download_dir, &local_name);
    // Atomic write: temp file then rename
    let tmp = download_dir.join(format!(".{}.tmp", &file_hash));
    let _ = std::fs::write(&tmp, &*file_bytes);
    let _ = std::fs::rename(&tmp, &local_path);
    let local_path_str = local_path.to_string_lossy().to_string();

    // === Generate image metadata (thumbhash + dimensions) for image files ===
    let img_meta = crypto::generate_image_metadata(&file_bytes);

    // === Encrypt → upload → build rumor → send ===
    let params = crypto::generate_encryption_params();
    let encrypted = crypto::encrypt_data(&file_bytes, &params)?;
    let encrypted_size = encrypted.len() as u64;

    let attachment = Attachment {
        id: file_hash.clone(), key: params.key.clone(), nonce: params.nonce.clone(),
        extension: extension.to_string(), name: filename.to_string(),
        url: String::new(), path: local_path_str.clone(), size: encrypted_size,
        img_meta: img_meta.clone(), downloading: false, downloaded: true,
        webxdc_topic: webxdc_topic.clone(),
        ..Default::default()
    };
    let msg = Message {
        id: pending_id.clone(), content: content.unwrap_or("").to_string(),
        at: now.as_millis() as u64, pending: true, mine: true,
        npub: my_pk.to_bech32().ok(), attachments: vec![attachment],
        ..Default::default()
    };
    {
        let mut state = STATE.lock().await;
        state.add_message_to_participant(receiver_npub, msg.clone());
    }
    callback.on_pending(receiver_npub, &msg);

    // Upload to Blossom — bridge SendCallback.on_upload_progress to Blossom ProgressCallback
    let servers = crate::state::get_blossom_servers();
    let cb_for_progress = callback.clone();
    let pid_for_progress = pending_id.clone();
    let progress_cb: crate::blossom::ProgressCallback = Arc::new(move |percentage, bytes| {
        cb_for_progress.on_upload_progress(
            &pid_for_progress,
            percentage.unwrap_or(0),
            bytes.unwrap_or(0),
        )
    });

    // Send the original MIME even though bytes are ciphertext: many
    // Blossom servers reject `application/octet-stream` but accept the
    // same bytes under their original type.
    let upload_url = match crate::blossom::upload_blob_with_progress_and_failover(
        signer.clone(), servers, Arc::new(encrypted), Some(mime_type),
        /* is_encrypted */ true,
        progress_cb, Some(config.upload_retries), Some(config.upload_retry_delay),
        config.cancel_token.clone(),
    ).await {
        Ok(url) => url,
        Err(e) => {
            let failed_msg = {
                let mut state = STATE.lock().await;
                state.update_message(&pending_id, |msg| {
                    msg.set_failed(true);
                    msg.set_pending(false);
                })
            };
            if let Some((_chat_id, ref msg)) = failed_msg {
                callback.on_failed(receiver_npub, &pending_id, msg);
                callback.on_persist(receiver_npub, msg);
            }
            return Err(format!("Upload failed: {}", e));
        }
    };

    {
        let mut state = STATE.lock().await;
        state.update_message(&pending_id, |msg| {
            if let Some(att) = msg.attachments.last_mut() {
                att.url = upload_url.clone().into_boxed_str();
            }
        });
    }
    callback.on_upload_complete(receiver_npub, &pending_id, &file_hash, &upload_url);

    // Build Kind 15
    let mut file_rumor = EventBuilder::new(Kind::from_u16(15), &upload_url)
        .tag(Tag::public_key(receiver))
        .tag(Tag::custom(TagKind::custom("file-type"), [mime_type]))
        .tag(Tag::custom(TagKind::custom("size"), [encrypted_size.to_string()]))
        .tag(Tag::custom(TagKind::custom("encryption-algorithm"), ["aes-gcm"]))
        .tag(Tag::custom(TagKind::custom("decryption-key"), [params.key.as_str()]))
        .tag(Tag::custom(TagKind::custom("decryption-nonce"), [params.nonce.as_str()]))
        .tag(Tag::custom(TagKind::custom("ox"), [file_hash.clone()]));
    if !filename.is_empty() {
        file_rumor = file_rumor.tag(Tag::custom(TagKind::custom("name"), [filename]));
    }
    if let Some(ref topic) = webxdc_topic {
        file_rumor = file_rumor.tag(Tag::custom(TagKind::custom("webxdc-topic"), [topic.as_str()]));
    }
    // Include image preview metadata for compatible rendering across all clients
    if let Some(ref meta) = img_meta {
        if !meta.thumbhash.is_empty() {
            file_rumor = file_rumor.tag(Tag::custom(TagKind::custom("thumb"), [meta.thumbhash.as_str()]));
        }
        file_rumor = file_rumor.tag(Tag::custom(TagKind::custom("dim"), [format!("{}x{}", meta.width, meta.height)]));
    }
    file_rumor = file_rumor.tag(Tag::custom(TagKind::custom("ms"), [milliseconds.to_string()]));

    let built_rumor = file_rumor.build(my_pk);
    let event_id = built_rumor.id.ok_or("Rumor has no id")?.to_hex();

    retry_send_gift_wrap(
        &client, &receiver, receiver_npub, &pending_id,
        built_rumor, &event_id, config, callback,
    ).await
}

// ============================================================================
// Tests
// ============================================================================

#[cfg(test)]
mod tests {
    use super::*;
    use std::sync::Mutex;

    #[derive(Debug, Clone, PartialEq)]
    enum CbEvent {
        Pending(String),
        UploadProgress(String, u8, u64),
        UploadComplete(String, String),
        Sent(String, String),
        Failed(String, String),
        Persist(String),
    }

    struct MockCallback {
        events: Mutex<Vec<CbEvent>>,
        cancel_at: Option<u8>,
    }

    impl MockCallback {
        fn new() -> Self { Self { events: Mutex::new(vec![]), cancel_at: None } }
        fn with_cancel(pct: u8) -> Self { Self { events: Mutex::new(vec![]), cancel_at: Some(pct) } }
        fn events(&self) -> Vec<CbEvent> { self.events.lock().unwrap().clone() }
    }

    impl SendCallback for MockCallback {
        fn on_pending(&self, cid: &str, _: &Message) {
            self.events.lock().unwrap().push(CbEvent::Pending(cid.into()));
        }
        fn on_upload_progress(&self, pid: &str, pct: u8, bytes: u64) -> Result<(), String> {
            self.events.lock().unwrap().push(CbEvent::UploadProgress(pid.into(), pct, bytes));
            if self.cancel_at.map_or(false, |c| pct >= c) { return Err("Cancelled".into()); }
            Ok(())
        }
        fn on_upload_complete(&self, cid: &str, _: &str, _: &str, url: &str) {
            self.events.lock().unwrap().push(CbEvent::UploadComplete(cid.into(), url.into()));
        }
        fn on_sent(&self, cid: &str, old: &str, _: &Message) {
            self.events.lock().unwrap().push(CbEvent::Sent(cid.into(), old.into()));
        }
        fn on_failed(&self, cid: &str, old: &str, _: &Message) {
            self.events.lock().unwrap().push(CbEvent::Failed(cid.into(), old.into()));
        }
        fn on_persist(&self, cid: &str, _: &Message) {
            self.events.lock().unwrap().push(CbEvent::Persist(cid.into()));
        }
    }

    #[test]
    fn config_default() {
        let c = SendConfig::default();
        assert_eq!(c.max_send_attempts, 1);
        assert!(!c.self_send);
        assert!(c.cancel_token.is_none());
        assert_eq!(c.upload_retries, 3);
    }

    #[test]
    fn config_gui() {
        let c = SendConfig::gui();
        assert_eq!(c.max_send_attempts, 12);
        assert!(c.self_send);
    }

    #[test]
    fn config_headless() {
        let c = SendConfig::headless();
        assert_eq!(c.max_send_attempts, 3);
        assert!(c.self_send);
    }

    #[test]
    fn config_custom_override() {
        let c = SendConfig { max_send_attempts: 5, ..SendConfig::gui() };
        assert_eq!(c.max_send_attempts, 5);
        assert!(c.self_send);
    }

    #[test]
    fn noop_callback_all_methods() {
        let cb = NoOpSendCallback;
        let msg = Message::default();
        cb.on_pending("c", &msg);

        assert!(cb.on_upload_progress("p", 50, 1024).is_ok());
        cb.on_upload_complete("c", "p", "a", "url");
        cb.on_sent("c", "o", &msg);
        cb.on_failed("c", "o", &msg);
        cb.on_persist("c", &msg);
    }

    #[test]
    fn text_dm_sequence() {
        let cb = MockCallback::new();
        let msg = Message::default();
        cb.on_pending("r", &msg);
        cb.on_sent("r", "p-1", &msg);
        cb.on_persist("r", &msg);
        assert_eq!(cb.events(), vec![
            CbEvent::Pending("r".into()),
            CbEvent::Sent("r".into(), "p-1".into()),
            CbEvent::Persist("r".into()),
        ]);
    }

    #[test]
    fn file_dm_sequence() {
        let cb = MockCallback::new();
        let msg = Message::default();
        cb.on_pending("r", &msg);

        cb.on_upload_progress("p", 0, 0).ok();
        cb.on_upload_progress("p", 50, 5000).ok();
        cb.on_upload_progress("p", 100, 10000).ok();
        cb.on_upload_complete("r", "p", "h", "https://blossom/h");
        cb.on_sent("r", "p", &msg);
        cb.on_persist("r", &msg);
        let e = cb.events();
        assert_eq!(e.len(), 7);
        assert!(matches!(&e[4], CbEvent::UploadComplete(_, url) if url.contains("blossom")));
    }

    #[test]
    fn failed_sequence() {
        let cb = MockCallback::new();
        let msg = Message::default();
        cb.on_pending("r", &msg);
        cb.on_failed("r", "p", &msg);
        cb.on_persist("r", &msg);
        assert_eq!(cb.events(), vec![
            CbEvent::Pending("r".into()),
            CbEvent::Failed("r".into(), "p".into()),
            CbEvent::Persist("r".into()),
        ]);
    }

    #[test]
    fn cancel_upload_at_threshold() {
        let cb = MockCallback::with_cancel(50);
        assert!(cb.on_upload_progress("p", 25, 512).is_ok());
        assert!(cb.on_upload_progress("p", 50, 1024).is_err());
        assert_eq!(cb.events().len(), 2);
    }

    #[test]
    fn cancel_triggers_failed() {
        let cb = MockCallback::with_cancel(30);
        let msg = Message::default();
        cb.on_pending("r", &msg);

        cb.on_upload_progress("p", 10, 1000).ok();
        assert!(cb.on_upload_progress("p", 30, 3000).is_err());
        cb.on_failed("r", "p", &msg);
        assert!(matches!(cb.events().last(), Some(CbEvent::Failed(..))));
    }

    #[test]
    fn send_result_serialize() {
        let r = SendResult { pending_id: "p".into(), event_id: Some("e".into()), chat_id: "c".into() };
        let j = serde_json::to_string(&r).unwrap();
        assert!(j.contains("\"pending_id\":\"p\""));
    }

    #[test]
    fn send_result_none_event() {
        let r = SendResult { pending_id: "p".into(), event_id: None, chat_id: "c".into() };
        let j = serde_json::to_string(&r).unwrap();
        assert!(j.contains("null"));
    }

    // ========================================================================
    // File DM callback sequences
    // ========================================================================

    #[test]
    fn file_dm_fresh_upload_full_sequence() {
        let cb = MockCallback::new();
        let msg = Message::default();

        // 1. Pending message created
        cb.on_pending("npub1recv", &msg);
        // 2. Attachment preview added

        // 3. Upload progress (0% → 25% → 50% → 75% → 100%)
        cb.on_upload_progress("pending-42", 0, 0).unwrap();
        cb.on_upload_progress("pending-42", 25, 2500).unwrap();
        cb.on_upload_progress("pending-42", 50, 5000).unwrap();
        cb.on_upload_progress("pending-42", 75, 7500).unwrap();
        cb.on_upload_progress("pending-42", 100, 10000).unwrap();
        // 4. Upload complete
        cb.on_upload_complete("npub1recv", "pending-42", "deadbeef", "https://blossom.example/deadbeef");
        // 5. Gift-wrap sent successfully
        cb.on_sent("npub1recv", "pending-42", &msg);
        // 6. Persisted to DB
        cb.on_persist("npub1recv", &msg);

        let e = cb.events();
        assert_eq!(e.len(), 9);
        assert!(matches!(&e[0], CbEvent::Pending(c) if c == "npub1recv"));
        assert!(matches!(&e[1], CbEvent::UploadProgress(_, 0, 0)));
        assert!(matches!(&e[5], CbEvent::UploadProgress(_, 100, 10000)));
        assert!(matches!(&e[6], CbEvent::UploadComplete(_, url) if url.contains("deadbeef")));
        assert!(matches!(&e[7], CbEvent::Sent(..)));
        assert!(matches!(&e[8], CbEvent::Persist(..)));
    }

    #[test]
    fn file_dm_skip_upload_sequence() {
        let cb = MockCallback::new();
        let msg = Message::default();

        // Dedup hit: no upload, existing URL reused
        // 1. Pending message
        cb.on_pending("npub1recv", &msg);
        // 2. Attachment preview (with reused URL already set)

        // 3. Upload complete (immediate — URL was already known)
        cb.on_upload_complete("npub1recv", "pending-99", "existinghash", "https://blossom.example/existing");
        // 4. Gift-wrap sent
        cb.on_sent("npub1recv", "pending-99", &msg);
        // 5. Persisted
        cb.on_persist("npub1recv", &msg);

        let e = cb.events();
        assert_eq!(e.len(), 4);
        // No UploadProgress events — upload was skipped
        assert!(!e.iter().any(|ev| matches!(ev, CbEvent::UploadProgress(..))));
        assert!(matches!(&e[1], CbEvent::UploadComplete(..)));
    }

    #[test]
    fn file_dm_upload_cancelled_at_30pct() {
        let cb = MockCallback::with_cancel(30);
        let msg = Message::default();

        cb.on_pending("npub1recv", &msg);

        assert!(cb.on_upload_progress("p", 10, 1000).is_ok());
        assert!(cb.on_upload_progress("p", 20, 2000).is_ok());
        // Cancel triggers at 30%
        let err = cb.on_upload_progress("p", 30, 3000);
        assert!(err.is_err());
        assert!(err.unwrap_err().contains("Cancelled"));
        // Pipeline marks as failed
        cb.on_failed("npub1recv", "p", &msg);

        let e = cb.events();
        assert_eq!(e.len(), 5);
        // No Sent, no Persist after cancel — just Failed
        assert!(!e.iter().any(|ev| matches!(ev, CbEvent::Sent(..))));
        assert!(matches!(e.last(), Some(CbEvent::Failed(..))));
    }

    #[test]
    fn file_dm_upload_fails_marks_failed() {
        let cb = MockCallback::new();
        let msg = Message::default();

        cb.on_pending("npub1recv", &msg);

        cb.on_upload_progress("p", 0, 0).ok();
        cb.on_upload_progress("p", 10, 500).ok();
        // Upload fails (server error, all retries exhausted)
        cb.on_failed("npub1recv", "p", &msg);
        cb.on_persist("npub1recv", &msg);

        let e = cb.events();
        assert_eq!(e.len(), 5);
        assert!(matches!(&e[3], CbEvent::Failed(..)));
        assert!(matches!(&e[4], CbEvent::Persist(..)));
        // No UploadComplete, no Sent
        assert!(!e.iter().any(|ev| matches!(ev, CbEvent::UploadComplete(..))));
        assert!(!e.iter().any(|ev| matches!(ev, CbEvent::Sent(..))));
    }

    #[test]
    fn file_dm_gift_wrap_fails_after_upload() {
        let cb = MockCallback::new();
        let msg = Message::default();

        // Upload succeeds but gift-wrap fails
        cb.on_pending("npub1recv", &msg);

        cb.on_upload_progress("p", 100, 10000).ok();
        cb.on_upload_complete("npub1recv", "p", "hash", "https://blossom/hash");
        // Gift-wrap retry exhausted
        cb.on_failed("npub1recv", "p", &msg);
        cb.on_persist("npub1recv", &msg);

        let e = cb.events();
        assert_eq!(e.len(), 5);
        // Upload succeeded but send failed
        assert!(matches!(&e[2], CbEvent::UploadComplete(..)));
        assert!(matches!(&e[3], CbEvent::Failed(..)));
    }

    #[test]
    fn file_dm_with_image_metadata_sequence() {
        let cb = MockCallback::new();
        let msg = Message::default();

        // Image with thumbhash + dimensions
        cb.on_pending("npub1recv", &msg);

        cb.on_upload_progress("p", 0, 0).ok();
        cb.on_upload_progress("p", 50, 50000).ok();
        cb.on_upload_progress("p", 100, 100000).ok();
        cb.on_upload_complete("npub1recv", "p", "imghash", "https://blossom/imghash.jpg");
        cb.on_sent("npub1recv", "p", &msg);
        cb.on_persist("npub1recv", &msg);

        let e = cb.events();
        assert_eq!(e.len(), 7);
        // Verify ordering: pending → progress(3x) → complete → sent → persist
        assert!(matches!(&e[0], CbEvent::Pending(..)));
        assert!(matches!(&e[4], CbEvent::UploadComplete(_, url) if url.ends_with(".jpg")));
        assert!(matches!(&e[5], CbEvent::Sent(..)));
    }

    #[test]
    fn cancel_token_config_with_upload() {
        let token = Arc::new(std::sync::atomic::AtomicBool::new(false));
        let c = SendConfig {
            cancel_token: Some(token.clone()),
            ..SendConfig::gui()
        };
        assert!(c.cancel_token.is_some());
        assert!(!token.load(std::sync::atomic::Ordering::Relaxed));

        // Simulate cancel
        token.store(true, std::sync::atomic::Ordering::Relaxed);
        assert!(c.cancel_token.as_ref().unwrap().load(std::sync::atomic::Ordering::Relaxed));
    }
}