zeptoclaw 0.9.0

Ultra-lightweight personal AI assistant
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
//! Email channel implementation — IMAP IDLE (inbound) + SMTP (outbound).
//!
//! Feature-gated behind `channel-email`:
//! - Without the feature: channel compiles but `start()` / `send()` return a
//!   clear error telling the user to rebuild.
//! - With the feature: full IMAP IDLE loop with automatic reconnect and SMTP
//!   send via STARTTLS.
//!
//! # Example configuration
//!
//! ```json
//! {
//!   "channels": {
//!     "email": {
//!       "imap_host": "imap.gmail.com",
//!       "smtp_host": "smtp.gmail.com",
//!       "username": "bot@gmail.com",
//!       "password": "app-password",
//!       "allowed_senders": ["@mycompany.com"]
//!     }
//!   }
//! }
//! ```
//!
//! `allowed_senders` is matched against the parsed inbound `From` header.
//! This is a trust-model limitation of IMAP/header-based ingestion, not a
//! cryptographic sender-authentication guarantee. If sender authenticity
//! matters, enforce SPF/DKIM/DMARC upstream before messages reach this channel.

#[cfg(feature = "channel-email")]
use futures::FutureExt;
#[cfg(feature = "channel-email")]
use tracing::{error, info, warn};

use async_trait::async_trait;
use std::collections::HashSet;
use std::sync::{
    atomic::{AtomicBool, Ordering},
    Arc,
};
use tokio::sync::Mutex;

#[cfg(feature = "channel-email")]
use crate::bus::{InboundMessage, MediaAttachment, MediaType};
use crate::bus::{MessageBus, OutboundMessage};
use crate::config::EmailConfig;
use crate::error::{Result, ZeptoError};

use super::{BaseChannelConfig, Channel};

// ---------------------------------------------------------------------------
// Channel struct (always compiled)
// ---------------------------------------------------------------------------

/// Email channel: IMAP IDLE for inbound push, SMTP for outbound.
///
/// This struct always compiles regardless of the `channel-email` feature.
/// Without the feature, `start()` and `send()` return a clear rebuild error.
#[cfg_attr(not(feature = "channel-email"), allow(dead_code))]
pub struct EmailChannel {
    config: EmailConfig,
    base_config: BaseChannelConfig,
    bus: Arc<MessageBus>,
    running: Arc<AtomicBool>,
    /// Tracks Message-IDs seen in the current session to avoid reprocessing on
    /// reconnect.
    seen_ids: Arc<Mutex<HashSet<String>>>,
}

impl EmailChannel {
    /// Create a new `EmailChannel` from configuration.
    pub fn new(config: EmailConfig, bus: Arc<MessageBus>) -> Self {
        #[cfg(feature = "channel-email")]
        if config.enabled && !config.allowed_senders.is_empty() {
            warn!(
                "Email allowed_senders relies on the parsed From header only. \
                 Enforce SPF/DKIM/DMARC upstream if sender authenticity matters."
            );
        }

        let base_config = BaseChannelConfig {
            name: "email".to_string(),
            allowlist: config.allowed_senders.clone(),
            deny_by_default: config.deny_by_default,
        };
        Self {
            config,
            base_config,
            bus,
            running: Arc::new(AtomicBool::new(false)),
            seen_ids: Arc::new(Mutex::new(HashSet::new())),
        }
    }

    /// Check whether the given sender email address is permitted.
    ///
    /// Rules (applied in order):
    /// 1. `"*"` in allowlist → allow all.
    /// 2. Exact address match (case-insensitive).
    /// 3. Domain with `@` prefix (`"@example.com"`) matches any address at that domain.
    /// 4. Domain without `@` prefix (`"example.com"`) also matches any address at that domain.
    /// 5. Empty allowlist + `deny_by_default = false` → allow all.
    /// 6. Empty allowlist + `deny_by_default = true` → deny all.
    pub fn is_sender_allowed(&self, from: &str) -> bool {
        let list = &self.config.allowed_senders;

        if list.is_empty() {
            return !self.config.deny_by_default;
        }

        if list.iter().any(|a| a == "*") {
            return true;
        }

        let from_lower = from.to_lowercase();
        list.iter().any(|allowed| {
            if allowed.starts_with('@') {
                from_lower.ends_with(&allowed.to_lowercase())
            } else if allowed.contains('@') {
                allowed.eq_ignore_ascii_case(from)
            } else {
                from_lower.ends_with(&format!("@{}", allowed.to_lowercase()))
            }
        })
    }

    /// Extract plain text body from a `mail_parser::Message`.
    ///
    /// Only available when the `channel-email` feature is enabled.
    #[cfg(feature = "channel-email")]
    pub fn extract_plain_text(msg: &mail_parser::Message) -> String {
        msg.body_text(0).map(|s| s.to_string()).unwrap_or_else(|| {
            msg.body_html(0)
                .map(|h| Self::strip_html(h.as_ref()))
                .unwrap_or_default()
        })
    }

    /// Naive HTML tag stripper (no external dep required).
    pub fn strip_html(html: &str) -> String {
        let mut out = String::with_capacity(html.len());
        let mut in_tag = false;
        for ch in html.chars() {
            match ch {
                '<' => in_tag = true,
                '>' => in_tag = false,
                _ if !in_tag => out.push(ch),
                _ => {}
            }
        }
        out.split_whitespace().collect::<Vec<_>>().join(" ")
    }

    // ------------------------------------------------------------------
    // Feature-gated internals
    // ------------------------------------------------------------------

    /// Connect to the IMAP server with implicit TLS (port 993) and authenticate.
    #[cfg(feature = "channel-email")]
    async fn connect_imap(
        &self,
    ) -> std::result::Result<
        async_imap::Session<tokio_rustls::client::TlsStream<tokio::net::TcpStream>>,
        ZeptoError,
    > {
        use rustls::{ClientConfig as RustlsClientConfig, RootCertStore};
        use tokio::net::TcpStream;
        use tokio_rustls::TlsConnector;

        let addr = format!("{}:{}", self.config.imap_host, self.config.imap_port);

        let tcp = TcpStream::connect(&addr)
            .await
            .map_err(|e| ZeptoError::Channel(format!("IMAP TCP connect failed: {e}")))?;

        let cert_store = RootCertStore {
            roots: webpki_roots::TLS_SERVER_ROOTS.into(),
        };
        let tls_cfg = RustlsClientConfig::builder()
            .with_root_certificates(cert_store)
            .with_no_client_auth();

        let connector = TlsConnector::from(Arc::new(tls_cfg));
        let sni = rustls::pki_types::ServerName::try_from(self.config.imap_host.clone())
            .map_err(|e| ZeptoError::Channel(format!("Invalid IMAP hostname: {e}")))?;

        let tls_stream = connector
            .connect(sni, tcp)
            .await
            .map_err(|e| ZeptoError::Channel(format!("IMAP TLS handshake failed: {e}")))?;

        let client = async_imap::Client::new(tls_stream);
        let session = client
            .login(&self.config.username, &self.config.password)
            .await
            .map_err(|(e, _)| ZeptoError::Channel(format!("IMAP login failed: {e}")))?;

        Ok(session)
    }

    /// Run a single IMAP IDLE session: connect → select mailbox → process
    /// existing unseen messages → IDLE loop.
    ///
    /// The `_stop` handle returned by `idle.wait()` is intentionally held until
    /// `idle.done()` is called. The IDLE timeout is capped at
    /// `config.idle_timeout_secs` (default 1740 s ≈ 29 min) so the loop
    /// re-checks `running` at least that often even without an explicit interrupt.
    #[cfg(feature = "channel-email")]
    async fn run_idle_session(&self) -> std::result::Result<(), ZeptoError> {
        use async_imap::extensions::idle::IdleResponse;
        use std::time::Duration;

        let mut session = self.connect_imap().await?;

        session
            .select(&self.config.imap_folder)
            .await
            .map_err(|e| ZeptoError::Channel(format!("IMAP SELECT failed: {e}")))?;

        info!(
            "Email IMAP IDLE listening on {} / {}",
            self.config.imap_host, self.config.imap_folder
        );

        self.process_unseen(&mut session).await?;

        loop {
            if !self.running.load(Ordering::SeqCst) {
                break;
            }

            let idle_timeout = Duration::from_secs(self.config.idle_timeout_secs);
            let mut idle = session.idle();

            idle.init()
                .await
                .map_err(|e| ZeptoError::Channel(format!("IDLE init failed: {e}")))?;

            let (wait_fut, _stop) = idle.wait();
            let idle_result = tokio::time::timeout(idle_timeout, wait_fut).await;

            session = idle
                .done()
                .await
                .map_err(|e| ZeptoError::Channel(format!("IDLE done failed: {e}")))?;

            match idle_result {
                Ok(Ok(IdleResponse::NewData(_))) => {
                    // New mail — process immediately.
                }
                Ok(Ok(IdleResponse::Timeout)) | Err(_) => {
                    // Server timeout or local timeout — defensive fetch then re-IDLE.
                }
                Ok(Ok(IdleResponse::ManualInterrupt)) => {
                    info!("IMAP IDLE interrupted — stopping email channel");
                    break;
                }
                Ok(Err(e)) => {
                    return Err(ZeptoError::Channel(format!("IDLE wait error: {e}")));
                }
            }

            self.process_unseen(&mut session).await?;
        }

        let _ = session.logout().await;
        Ok(())
    }

    /// Fetch UNSEEN messages, deduplicate, filter by allowlist, and publish to bus.
    #[cfg(feature = "channel-email")]
    async fn process_unseen(
        &self,
        session: &mut async_imap::Session<tokio_rustls::client::TlsStream<tokio::net::TcpStream>>,
    ) -> std::result::Result<(), ZeptoError> {
        use futures::TryStreamExt;
        use mail_parser::MessageParser;

        let uids = session
            .uid_search("UNSEEN")
            .await
            .map_err(|e| ZeptoError::Channel(format!("IMAP SEARCH UNSEEN failed: {e}")))?;

        if uids.is_empty() {
            return Ok(());
        }

        let uid_set = uids
            .iter()
            .map(|u| u.to_string())
            .collect::<Vec<_>>()
            .join(",");

        let raw_messages: Vec<async_imap::types::Fetch> = session
            .uid_fetch(&uid_set, "RFC822")
            .await
            .map_err(|e| ZeptoError::Channel(format!("IMAP FETCH failed: {e}")))?
            .try_collect()
            .await
            .map_err(|e| ZeptoError::Channel(format!("IMAP FETCH stream failed: {e}")))?;

        let parser = MessageParser::default();
        let inbound_tx = self.bus.inbound_sender();

        for raw in &raw_messages {
            let body = match raw.body() {
                Some(b) => b,
                None => continue,
            };

            let parsed = match parser.parse(body) {
                Some(m) => m,
                None => {
                    warn!("Failed to parse email body");
                    continue;
                }
            };

            let msg_id = parsed
                .message_id()
                .map(|s| s.to_string())
                .unwrap_or_else(|| format!("gen-{}", uuid::Uuid::new_v4()));

            let from = parsed
                .from()
                .and_then(|a| a.first())
                .and_then(|a| a.address())
                .map(|s| s.to_string())
                .unwrap_or_else(|| "unknown".into());

            // Dedup BEFORE allowlist check so blocked messages are not
            // re-warned on every reconnect.
            let is_new = {
                let mut seen = self.seen_ids.lock().await;
                seen.insert(msg_id.clone())
            };
            if !is_new {
                continue;
            }

            if !self.is_sender_allowed(&from) {
                warn!("Blocked email from {from}");
                continue;
            }

            let subject = parsed.subject().unwrap_or("(no subject)").to_string();
            let body_text = Self::extract_plain_text(&parsed);
            let content = format!("Subject: {subject}\n\n{body_text}");

            let mut inbound = InboundMessage::new("email", &from, &from, &content)
                .with_metadata("message_id", &msg_id)
                .with_metadata("subject", &subject);

            // Extract image attachments
            use mail_parser::MimeHeaders;
            for part in parsed.attachments() {
                if let Some(ct) = part.content_type() {
                    let main_type = ct.c_type.as_ref();
                    let sub_type = ct.c_subtype.as_deref().unwrap_or("octet-stream");
                    let mime = format!("{}/{}", main_type, sub_type);
                    if main_type.eq_ignore_ascii_case("image") {
                        let bytes = part.contents().to_vec();
                        if !bytes.is_empty() && bytes.len() <= 20 * 1024 * 1024 {
                            let mut media = MediaAttachment::new(MediaType::Image)
                                .with_data(bytes)
                                .with_mime_type(&mime);
                            if let Some(name) = part.attachment_name() {
                                media = media.with_filename(name);
                            }
                            inbound = inbound.with_media(media);
                        }
                    }
                }
            }

            if inbound_tx.send(inbound).await.is_err() {
                return Ok(());
            }
        }

        // Mark fetched messages as \Seen.
        if !raw_messages.is_empty() {
            let _ = session.uid_store(&uid_set, "+FLAGS (\\Seen)").await;
        }

        Ok(())
    }
}

// ---------------------------------------------------------------------------
// Channel trait implementation
// ---------------------------------------------------------------------------

#[async_trait]
impl Channel for EmailChannel {
    fn name(&self) -> &str {
        "email"
    }

    async fn start(&mut self) -> Result<()> {
        #[cfg(not(feature = "channel-email"))]
        {
            return Err(ZeptoError::Channel(
                "Email channel requires the 'channel-email' build feature. \
                 Rebuild with: cargo build --features channel-email"
                    .into(),
            ));
        }

        #[cfg(feature = "channel-email")]
        {
            // Fix 4: atomic swap prevents a double-start race condition.
            if self.running.swap(true, Ordering::SeqCst) {
                warn!("Email channel already running");
                return Ok(());
            }

            let config = self.config.clone();
            let bus = Arc::clone(&self.bus);
            let seen_ids = Arc::clone(&self.seen_ids);
            let this_running = Arc::clone(&self.running);

            tokio::spawn(async move {
                let task_result = std::panic::AssertUnwindSafe(async move {
                    let channel = EmailChannel {
                        config,
                        base_config: BaseChannelConfig::new("email"),
                        bus,
                        running: Arc::clone(&this_running),
                        seen_ids,
                    };

                    let mut backoff = std::time::Duration::from_secs(1);
                    let max_backoff = std::time::Duration::from_secs(60);

                    while this_running.load(Ordering::SeqCst) {
                        match channel.run_idle_session().await {
                            Ok(()) => break,
                            Err(e) => {
                                error!(
                                    "Email IMAP session error: {e}. Reconnecting in {backoff:?}…"
                                );
                                tokio::time::sleep(backoff).await;
                                backoff = std::cmp::min(backoff * 2, max_backoff);
                            }
                        }
                    }
                })
                .catch_unwind()
                .await;
                if task_result.is_err() {
                    error!("Email channel task panicked");
                }

                this_running.store(false, Ordering::SeqCst);
                info!("Email channel stopped");
            });

            info!(
                "Email channel starting (IMAP IDLE on {})",
                self.config.imap_host
            );
            if !self.config.allowed_senders.is_empty() {
                warn!(
                    "Email allowed_senders checks parsed From headers only; \
                     configure authenticated-mail enforcement upstream if sender authenticity matters."
                );
            }
            Ok(())
        }
    }

    async fn stop(&mut self) -> Result<()> {
        // Fix 3: use SeqCst to match the rest of the codebase.
        // The IDLE loop re-checks `running` on each timeout (≤ idle_timeout_secs),
        // so shutdown latency is bounded without needing extra plumbing.
        self.running.store(false, Ordering::SeqCst);
        Ok(())
    }

    async fn send(&self, msg: OutboundMessage) -> Result<()> {
        #[cfg(not(feature = "channel-email"))]
        {
            let _ = msg;
            return Err(ZeptoError::Channel(
                "Email channel requires the 'channel-email' build feature. \
                 Rebuild with: cargo build --features channel-email"
                    .into(),
            ));
        }

        #[cfg(feature = "channel-email")]
        {
            // Fix 1: use async SMTP transport so we don't block the Tokio thread.
            use lettre::{
                message::SinglePart, transport::smtp::authentication::Credentials,
                AsyncSmtpTransport, AsyncTransport, Message as LettreMessage, Tokio1Executor,
            };

            let (subject, body) = if msg.content.starts_with("Subject: ") {
                if let Some(pos) = msg.content.find("\n\n") {
                    (
                        msg.content[9..pos].to_string(),
                        msg.content[pos + 2..].to_string(),
                    )
                } else if let Some(pos) = msg.content.find('\n') {
                    (
                        msg.content[9..pos].to_string(),
                        msg.content[pos + 1..].to_string(),
                    )
                } else {
                    ("ZeptoClaw Message".to_string(), msg.content.clone())
                }
            } else {
                ("ZeptoClaw Message".to_string(), msg.content.clone())
            };

            let from_addr = if let Some(ref name) = self.config.display_name {
                format!("{name} <{}>", self.config.username)
            } else {
                self.config.username.clone()
            };

            let email = LettreMessage::builder()
                .from(
                    from_addr
                        .parse()
                        .map_err(|e| ZeptoError::Channel(format!("Invalid from address: {e}")))?,
                )
                .to(msg
                    .chat_id
                    .parse()
                    .map_err(|e| ZeptoError::Channel(format!("Invalid to address: {e}")))?)
                .subject(subject)
                .singlepart(SinglePart::plain(body))
                .map_err(|e| ZeptoError::Channel(format!("Failed to build email: {e}")))?;

            let creds =
                Credentials::new(self.config.username.clone(), self.config.password.clone());

            let transport =
                AsyncSmtpTransport::<Tokio1Executor>::starttls_relay(&self.config.smtp_host)
                    .map_err(|e| ZeptoError::Channel(format!("SMTP relay error: {e}")))?
                    .port(self.config.smtp_port)
                    .credentials(creds)
                    .build();

            transport
                .send(email)
                .await
                .map_err(|e| ZeptoError::Channel(format!("SMTP send failed: {e}")))?;

            info!("Email sent to {}", msg.chat_id);
            Ok(())
        }
    }

    fn is_running(&self) -> bool {
        self.running.load(Ordering::SeqCst)
    }

    fn is_allowed(&self, user_id: &str) -> bool {
        self.base_config.is_allowed(user_id)
    }
}

// ---------------------------------------------------------------------------
// Unit tests
// ---------------------------------------------------------------------------

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

    fn make_config() -> EmailConfig {
        EmailConfig {
            imap_host: "imap.example.com".into(),
            imap_port: 993,
            smtp_host: "smtp.example.com".into(),
            smtp_port: 587,
            username: "bot@example.com".into(),
            password: "secret".into(),
            imap_folder: "INBOX".into(),
            display_name: Some("My Bot".into()),
            allowed_senders: vec![],
            deny_by_default: false,
            idle_timeout_secs: 1740,
            enabled: false,
        }
    }

    fn make_channel(config: EmailConfig) -> EmailChannel {
        let bus = Arc::new(MessageBus::new());
        EmailChannel::new(config, bus)
    }

    // ---- sender allowlist tests ----

    #[test]
    fn test_sender_allowed_empty_list() {
        // deny_by_default = false, allowed_senders empty → allow all
        let ch = make_channel(make_config());
        assert!(ch.is_sender_allowed("anyone@example.com"));
        assert!(ch.is_sender_allowed("random@test.org"));
    }

    #[test]
    fn test_sender_filtered_by_allowlist() {
        let mut cfg = make_config();
        cfg.allowed_senders = vec!["allowed@example.com".into()];
        let ch = make_channel(cfg);
        assert!(ch.is_sender_allowed("allowed@example.com"));
        assert!(!ch.is_sender_allowed("blocked@example.com"));
    }

    #[test]
    fn test_sender_case_insensitive() {
        let mut cfg = make_config();
        cfg.allowed_senders = vec!["Allowed@Example.COM".into()];
        let ch = make_channel(cfg);
        assert!(ch.is_sender_allowed("allowed@example.com"));
        assert!(ch.is_sender_allowed("ALLOWED@EXAMPLE.COM"));
        assert!(ch.is_sender_allowed("AlLoWeD@eXaMpLe.cOm"));
    }

    #[test]
    fn test_sender_wildcard_allows_all() {
        let mut cfg = make_config();
        cfg.allowed_senders = vec!["*".into()];
        let ch = make_channel(cfg);
        assert!(ch.is_sender_allowed("anyone@anywhere.com"));
    }

    #[test]
    fn test_sender_domain_with_at_prefix() {
        let mut cfg = make_config();
        cfg.allowed_senders = vec!["@example.com".into()];
        let ch = make_channel(cfg);
        assert!(ch.is_sender_allowed("user@example.com"));
        assert!(ch.is_sender_allowed("admin@example.com"));
        assert!(!ch.is_sender_allowed("user@other.com"));
    }

    #[test]
    fn test_sender_domain_without_at_prefix() {
        let mut cfg = make_config();
        cfg.allowed_senders = vec!["example.com".into()];
        let ch = make_channel(cfg);
        assert!(ch.is_sender_allowed("user@example.com"));
        assert!(!ch.is_sender_allowed("user@other.com"));
    }

    // ---- dedup tests ----

    #[tokio::test]
    async fn test_dedup_new_id_accepted() {
        let ch = make_channel(make_config());
        let mut seen = ch.seen_ids.lock().await;
        assert!(seen.insert("msg-001".to_string()));
    }

    #[tokio::test]
    async fn test_dedup_duplicate_rejected() {
        let ch = make_channel(make_config());
        let mut seen = ch.seen_ids.lock().await;
        seen.insert("msg-dup".to_string());
        assert!(!seen.insert("msg-dup".to_string()));
    }

    // ---- name test ----

    #[test]
    fn test_channel_name() {
        let ch = make_channel(make_config());
        assert_eq!(ch.name(), "email");
    }

    // ---- config defaults ----

    #[test]
    fn test_config_default_ports() {
        let cfg = EmailConfig::default();
        assert_eq!(cfg.imap_port, 993);
        assert_eq!(cfg.smtp_port, 587);
    }

    #[test]
    fn test_config_default_folder() {
        let cfg = EmailConfig::default();
        assert_eq!(cfg.imap_folder, "INBOX");
    }

    #[test]
    fn test_config_default_idle_timeout() {
        let cfg = EmailConfig::default();
        assert_eq!(cfg.idle_timeout_secs, 1740);
    }

    // ---- deny_by_default tests ----

    #[test]
    fn test_deny_by_default_false_allows_all() {
        let mut cfg = make_config();
        cfg.deny_by_default = false;
        cfg.allowed_senders = vec![];
        let ch = make_channel(cfg);
        assert!(ch.is_sender_allowed("anyone@example.com"));
    }

    #[test]
    fn test_deny_by_default_true_with_empty_allowlist() {
        let mut cfg = make_config();
        cfg.deny_by_default = true;
        cfg.allowed_senders = vec![];
        let ch = make_channel(cfg);
        assert!(!ch.is_sender_allowed("anyone@example.com"));
    }

    // ---- feature-gated extract_plain_text ----

    #[cfg(feature = "channel-email")]
    #[test]
    fn test_extract_plain_text_from_email() {
        let raw = b"From: sender@example.com\r\n\
                    To: bot@example.com\r\n\
                    Subject: Test\r\n\
                    Content-Type: text/plain; charset=UTF-8\r\n\
                    \r\n\
                    Hello, world!\r\n";

        let parsed = mail_parser::MessageParser::default()
            .parse(raw.as_ref())
            .expect("parse failed");
        let text = EmailChannel::extract_plain_text(&parsed);
        assert!(text.contains("Hello, world!"), "got: {text}");
    }

    // ---- serde roundtrip ----

    #[test]
    fn test_config_serde_roundtrip() {
        let json = serde_json::json!({
            "imap_host": "imap.gmail.com",
            "smtp_host": "smtp.gmail.com",
            "username": "user@gmail.com",
            "password": "pass"
        });
        let cfg: EmailConfig = serde_json::from_value(json).unwrap();
        assert_eq!(cfg.imap_port, 993);
        assert_eq!(cfg.smtp_port, 587);
        assert_eq!(cfg.imap_folder, "INBOX");
        assert!(!cfg.deny_by_default);
        assert!(cfg.allowed_senders.is_empty());
    }

    // ---- strip_html helper ----

    #[test]
    fn test_strip_html_basic() {
        assert_eq!(EmailChannel::strip_html("<p>Hello</p>"), "Hello");
        assert_eq!(EmailChannel::strip_html("<b>World</b>"), "World");
    }

    #[test]
    fn test_strip_html_no_tags() {
        assert_eq!(EmailChannel::strip_html("plain text"), "plain text");
        assert_eq!(EmailChannel::strip_html(""), "");
    }

    // ---- is_running default ----

    #[test]
    fn test_is_running_default_false() {
        let ch = make_channel(make_config());
        assert!(!ch.is_running());
    }

    // ---- enabled field ----

    #[test]
    fn test_config_enabled_default_false() {
        let cfg = EmailConfig::default();
        assert!(!cfg.enabled);
    }

    #[test]
    fn test_config_enabled_serde() {
        let json = serde_json::json!({
            "imap_host": "imap.gmail.com",
            "smtp_host": "smtp.gmail.com",
            "username": "user@gmail.com",
            "password": "pass",
            "enabled": true
        });
        let cfg: EmailConfig = serde_json::from_value(json).unwrap();
        assert!(cfg.enabled);
    }
}