supercode-cli 0.4.19

supercode — a lightweight, fully-customizable AI coding agent CLI in Rust. Any model via OpenRouter; natively continues Claude Code and Codex sessions.
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
//! UX-22: turn-finish notifications (desktop + optional email).
//!
//! supercode gives no signal when a long turn finishes — no bell, no
//! desktop popup. This module adds both, entirely opt-in and best-effort:
//!
//! - **Desktop**: shells out to `notify-send` (the standard libnotify CLI
//!   on Linux desktops), the same zero-new-dependency shape as
//!   `terminal_title.rs`'s raw OSC escapes — no `notify-rust`/dbus crate.
//!   `osascript` (macOS) / a toast API (Windows) are out of scope: this
//!   codebase only ships/tests on Linux (see `Cargo.toml`), and the box
//!   this was built on is headless Linux with no guaranteed dbus session —
//!   see [`fire_desktop`]'s doc for exactly how that's handled.
//! - **Bell**: a plain `BEL` (`\x07`) to stderr, the low-tech fallback the
//!   backlog's approach sketch pairs with the desktop notification.
//! - **Email** (optional/stretch per the backlog item): a minimal,
//!   dependency-free SMTP client — see [`fire_email`]'s doc for its scope
//!   and honest limitations (no TLS/STARTTLS).
//!
//! ## Gating (the AC)
//!
//! [`should_notify`] is the single choke point, mirroring
//! `terminal_title::should_set_title` / `spinner::should_show_spinner`'s
//! "one pure predicate, every call site funnels through it" shape:
//! off unless explicitly enabled (flag/env/config), never for a machine
//! output format (`json`/`stream-json`), never when stderr isn't a real
//! terminal (piped/CI — the AC's "non-interactive/piped" case), and only
//! for turns that actually ran long enough to matter.
//!
//! ## Never blocks, never breaks the turn
//!
//! [`maybe_fire`] is called AFTER a turn's own result is already decided
//! (the reply is already printed/persisted by the caller) — everything it
//! does is either near-instant (the `notify-send` `spawn()` call itself:
//! fork+exec, no wait for the child) or pushed onto a detached background
//! thread ([`fire_desktop`]'s reap, all of [`fire_email`]) whose failure
//! or slowness is invisible to (and can never fail) the turn that already
//! finished. Nothing here ever panics or returns a `Result` the caller
//! must handle — every failure mode (notifier absent, PATH lookup fails,
//! SMTP connect refused, ...) is swallowed at the source.
//!
//! ## Honest headless caveat
//!
//! This box has no guaranteed dbus session / `notify-send` binary. The
//! integration test (`crates/cli/tests/notify_cli.rs`) proves the WIRING —
//! a fake `notify-send` script on `PATH` receives the exact title/body —
//! and separately proves the "no `notify-send` on `PATH` at all" case
//! degrades to a silent no-op. Neither proves a real desktop popup was
//! ever rendered on a real display; that half is unverifiable here by
//! construction (no display, no dbus, no windowing system on this box).

use std::io::Write;
use std::process::{Command, Stdio};
use std::time::Duration;

/// Default "long turn" threshold (seconds) — a turn that finishes faster
/// than this is assumed to still be watched, so no notification fires.
/// Overridable via `--notify-threshold-secs` / `notify_threshold_secs`
/// config.
pub const DEFAULT_THRESHOLD_SECS: u64 = 30;

/// Cap on the reply/prompt preview folded into a notification body — a
/// short "safe summary" per the driver directive, never the full session.
pub const SUMMARY_MAX_CHARS: usize = 80;

/// Resolved notification settings for one CLI invocation — already merged
/// (flag > env > config > default), the same shape as `main.rs`'s other
/// `effective_*` helpers (e.g. `effective_reduced`).
#[derive(Debug, Clone, Default)]
pub struct NotifySettings {
    pub enabled: bool,
    pub threshold: Duration,
    pub email: Option<EmailConfig>,
    /// P5-7: the resolved lifecycle-hook set for this invocation, carried
    /// here because `NotifySettings` is already threaded to every turn-finish
    /// site. The `notification` hook (CC `Notification`, type
    /// `agent_completed`) fires from [`maybe_fire`] on each completed turn.
    /// Default (no `notification` command configured) = a hard no-op, so an
    /// invocation with no `[hooks]` set is byte-identical to before.
    pub hooks: crate::hooks::HookSet,
    /// P5-7: honored by the `notification` hook's chrome suppression (a
    /// SUCCESSFUL hook's own stdout is suppressed under `--quiet`; a
    /// failure/timeout is always reported).
    pub quiet: bool,
}

/// SMTP settings for the optional email channel. The account password is
/// deliberately NOT a field here (see `fire_email`'s doc) — it's read only
/// from the `SUPERCODE_NOTIFY_EMAIL_PASSWORD` env var at send time, so it
/// never has to live in a plaintext `config.toml`.
#[derive(Debug, Clone)]
pub struct EmailConfig {
    pub smtp_host: String,
    pub smtp_port: u16,
    pub from: String,
    pub to: String,
    pub username: Option<String>,
}

/// Pure gating decision — no I/O, unit-testable without a real tty,
/// notify-send, or network. A notification is suppressed unless ALL of:
///
/// - `enabled` — explicit opt-in (`--notify`, `SUPERCODE_NOTIFY`, or
///   `notify = true` in config). Off by default (AC dev/02).
/// - `!machine_format` — `--output-format json`/`stream-json` never
///   notifies. Those are scripted/wrapper callers; a stray notify-send
///   spawn (or, worse, any byte near stdout) is exactly the kind of side
///   effect a machine caller doesn't want.
/// - `stderr_is_tty` — the rest of "non-interactive/piped" (AC dev/02):
///   redirected/piped stderr (or CI) means nobody's at the terminal to
///   see a desktop notification anyway — the same non-tty gate
///   `terminal_title::should_set_title` uses.
/// - `elapsed >= threshold` — only turns long enough that the user might
///   plausibly have looked away (the backlog's "long-running turn").
pub fn should_notify(
    enabled: bool,
    machine_format: bool,
    stderr_is_tty: bool,
    elapsed: Duration,
    threshold: Duration,
) -> bool {
    enabled && !machine_format && stderr_is_tty && elapsed >= threshold
}

/// Strip control characters and cap length. A crafted assistant reply (or
/// user prompt) must never be able to smuggle control bytes into a
/// notify-send argument or an SMTP header, and the AC/driver directive
/// both call for a short SAFE summary, not the raw session content.
fn sanitize_summary(s: &str, max_chars: usize) -> String {
    let cleaned: String = s.chars().filter(|c| !c.is_control()).collect();
    let trimmed = cleaned.trim();
    if trimmed.chars().count() > max_chars {
        let truncated: String = trimmed.chars().take(max_chars).collect();
        format!("{truncated}")
    } else {
        trimmed.to_string()
    }
}

/// Build the `(title, body)` for a finished turn. `reply_preview` is the
/// model's OWN final reply text — truncated and control-stripped so at
/// most a short, safe preview ever leaves the process, never the full
/// history/session.
pub fn build_payload(model: &str, elapsed: Duration, reply_preview: &str) -> (String, String) {
    let title = "supercode: turn finished".to_string();
    let secs = elapsed.as_secs();
    let summary = sanitize_summary(reply_preview, SUMMARY_MAX_CHARS);
    let body = if summary.is_empty() {
        format!("{model} · {secs}s")
    } else {
        format!("{model} · {secs}s · {summary}")
    };
    (title, body)
}

/// Desktop notification via `notify-send`. The `Command::spawn()` call
/// itself runs SYNCHRONOUSLY on the caller's thread — that's just a
/// PATH-lookup + fork+exec, sub-millisecond in practice, and critically
/// must happen before this function returns: if it were pushed onto a
/// background thread instead, a fast-exiting `run` invocation could reach
/// `std::process::exit` before the OS ever scheduled that thread, and the
/// notify-send process would never launch at all. Once spawned, though,
/// `notify-send` is a fully independent OS process — supercode exiting
/// (or this Rust process's threads dying) afterward can't stop it or
/// prevent it from actually showing the popup.
///
/// Only the REAPING (`.wait()`, so the child doesn't sit as a zombie for
/// the rest of a long-lived `chat` REPL process) is pushed to a detached
/// background thread — that part is allowed to be slow/never-observed
/// without affecting anything (worst case for a short-lived `run`
/// process: the zombie is reparented to init on exit and reaped there,
/// same as any other orphaned child).
///
/// Degrades completely silently when `notify-send` isn't on `PATH`, dbus
/// isn't reachable, or spawning fails for any other reason — `spawn()`
/// returning `Err` is the ordinary "notifier absent" case, not an error
/// condition worth surfacing (AC dev/02: "never break the run if the
/// notifier is absent").
pub fn fire_desktop(title: &str, body: &str) {
    let child = Command::new("notify-send")
        .arg("--app-name=supercode")
        .arg(title)
        .arg(body)
        .stdin(Stdio::null())
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .spawn();
    if let Ok(mut child) = child {
        std::thread::spawn(move || {
            let _ = child.wait();
        });
    }
    // Err (not found / permission / etc.): silently no-op — the
    // "notifier absent" degrade-gracefully case, by construction.
}

/// Best-effort terminal bell (`BEL`) — the backlog's approach sketch pairs
/// this with the desktop notification. Stderr only, never stdout, and only
/// ever called from behind the same `should_notify` gate as the desktop
/// notification, so it inherits the same non-machine/interactive-only
/// discipline.
pub fn ring_bell() {
    let mut err = std::io::stderr();
    let _ = err.write_all(b"\x07");
    let _ = err.flush();
}

/// Fire-and-forget email notification (optional/stretch channel): a
/// minimal, dependency-free SMTP client (EHLO / optional AUTH LOGIN /
/// MAIL FROM / RCPT TO / DATA / QUIT) over a plain `TcpStream`.
///
/// **Honest scope**: this speaks UNENCRYPTED SMTP only — no STARTTLS, no
/// implicit TLS. It works against a local unauthenticated relay
/// (postfix/msmtp/sendmail on port 25) or a relay that accepts AUTH LOGIN
/// over a plaintext channel — it will NOT work against a TLS-required
/// provider like `smtp.gmail.com:587`. Adding STARTTLS would need a TLS
/// implementation (a new dependency, cargo-deny-relevant), which is out
/// of scope for a "prefer no new dep" stretch channel. This matches the
/// backlog's own framing of email as a stretch, config-gated addition,
/// not a production MTA client.
///
/// Runs entirely on a detached background thread — the SMTP round trip is
/// real network I/O (bounded by a 5s connect/read/write timeout, but
/// still potentially slow), so it must never run on the turn's own
/// thread. Any failure (DNS, connect refused, timeout, relay rejection)
/// is swallowed inside [`send_email_blocking`]'s `Result` and never
/// propagates — email is a best-effort side channel, same discipline as
/// the desktop notification.
///
/// Known limitation: because this is fully backgrounded, a single-shot
/// `run` invocation that exits immediately after printing its result can
/// race the SMTP conversation to completion — there's no bounded join at
/// the call site (unlike the desktop path's synchronous `spawn()`, the
/// email path has no equivalent "at least got launched" guarantee against
/// process exit). `chat`'s longer-lived REPL process gives this far more
/// headroom in practice. Config-gated and off by default, so this is a
/// documented trade-off rather than a silent one.
pub fn fire_email(cfg: EmailConfig, subject: &str, body: &str) {
    let subject = subject.to_string();
    let body = body.to_string();
    std::thread::spawn(move || {
        let _ = send_email_blocking(&cfg, &subject, &body);
    });
}

/// Dispatch whatever's configured (bell + desktop + optional email) for a
/// finished turn, subject to [`should_notify`]'s gating. The single call
/// site every command path (`run`, `chat`, `resume`) should use.
pub fn maybe_fire(
    settings: &NotifySettings,
    machine_format: bool,
    stderr_is_tty: bool,
    elapsed: Duration,
    model: &str,
    reply_preview: &str,
) {
    // P5-7: the `notification` lifecycle hook (CC `Notification`, type
    // `agent_completed`) fires at every completed turn — its OWN opt-in (a
    // configured command), independent of the desktop-notify `enabled`/tty/
    // threshold gate below, so a consumer can react to turn completions
    // without also enabling desktop pop-ups. Still suppressed for
    // machine-format runs (json/stream-json), matching the "no side effects
    // for a scripted caller" discipline the desktop path uses. A hard no-op
    // when no `notification` command is configured (`fire_notification`).
    if !machine_format {
        crate::hooks::fire_notification(
            &settings.hooks,
            model,
            elapsed.as_secs(),
            reply_preview,
            settings.quiet,
        );
    }
    if !should_notify(
        settings.enabled,
        machine_format,
        stderr_is_tty,
        elapsed,
        settings.threshold,
    ) {
        return;
    }
    let (title, body) = build_payload(model, elapsed, reply_preview);
    ring_bell();
    fire_desktop(&title, &body);
    if let Some(email) = &settings.email {
        fire_email(email.clone(), &title, &body);
    }
}

// ---- minimal SMTP client ----------------------------------------------

fn write_line(w: &mut impl Write, line: &str) -> std::io::Result<()> {
    w.write_all(line.as_bytes())?;
    w.write_all(b"\r\n")?;
    w.flush()
}

/// Read one SMTP reply (possibly multi-line, `XXX-` continuation until a
/// final `XXX ` line) and return the 3-digit status code. Bails with an
/// `InvalidData` error on a code outside 200-399 (SMTP failure), so the
/// caller's `?`-chain naturally aborts the conversation on the first
/// rejected step rather than plowing ahead with garbage state.
fn read_reply(r: &mut impl std::io::BufRead) -> std::io::Result<u32> {
    let mut code: u32;
    loop {
        let mut line = String::new();
        if r.read_line(&mut line)? == 0 {
            return Err(std::io::Error::new(
                std::io::ErrorKind::UnexpectedEof,
                "SMTP connection closed mid-reply",
            ));
        }
        let bytes = line.as_bytes();
        if bytes.len() < 4 {
            return Err(std::io::Error::new(
                std::io::ErrorKind::InvalidData,
                "malformed SMTP reply line",
            ));
        }
        code = std::str::from_utf8(&bytes[..3])
            .ok()
            .and_then(|s| s.parse().ok())
            .ok_or_else(|| {
                std::io::Error::new(std::io::ErrorKind::InvalidData, "non-numeric SMTP code")
            })?;
        let last = bytes[3] != b'-'; // '-' = continuation line, ' '/'\t' = final.
        if last {
            break;
        }
    }
    if !(200..400).contains(&code) {
        return Err(std::io::Error::other(format!(
            "SMTP command rejected, code {code}"
        )));
    }
    Ok(code)
}

fn send_email_blocking(cfg: &EmailConfig, subject: &str, body: &str) -> std::io::Result<()> {
    use base64::Engine;
    use std::io::BufReader;
    use std::net::{TcpStream, ToSocketAddrs};

    let addr = (cfg.smtp_host.as_str(), cfg.smtp_port)
        .to_socket_addrs()?
        .next()
        .ok_or_else(|| {
            std::io::Error::new(std::io::ErrorKind::NotFound, "SMTP host did not resolve")
        })?;
    let stream = TcpStream::connect_timeout(&addr, Duration::from_secs(5))?;
    stream.set_read_timeout(Some(Duration::from_secs(5)))?;
    stream.set_write_timeout(Some(Duration::from_secs(5)))?;
    let mut reader = BufReader::new(stream.try_clone()?);
    let mut writer = stream;

    read_reply(&mut reader)?; // 220 greeting
    write_line(&mut writer, "EHLO supercode.local")?;
    read_reply(&mut reader)?;

    if let Some(user) = &cfg.username {
        let password = std::env::var("SUPERCODE_NOTIFY_EMAIL_PASSWORD").unwrap_or_default();
        let b64 = base64::engine::general_purpose::STANDARD;
        write_line(&mut writer, "AUTH LOGIN")?;
        read_reply(&mut reader)?;
        write_line(&mut writer, &b64.encode(user))?;
        read_reply(&mut reader)?;
        write_line(&mut writer, &b64.encode(password))?;
        read_reply(&mut reader)?;
    }

    write_line(&mut writer, &format!("MAIL FROM:<{}>", cfg.from))?;
    read_reply(&mut reader)?;
    write_line(&mut writer, &format!("RCPT TO:<{}>", cfg.to))?;
    read_reply(&mut reader)?;
    write_line(&mut writer, "DATA")?;
    read_reply(&mut reader)?;
    write_line(&mut writer, &format!("Subject: {subject}"))?;
    write_line(&mut writer, &format!("From: {}", cfg.from))?;
    write_line(&mut writer, &format!("To: {}", cfg.to))?;
    write_line(&mut writer, "")?;
    write_line(&mut writer, body)?;
    write_line(&mut writer, ".")?;
    read_reply(&mut reader)?;
    write_line(&mut writer, "QUIT")?;
    let _ = read_reply(&mut reader);
    Ok(())
}

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

    // ---- should_notify: the gating predicate, exhaustive over each input
    // flipping independently (non-vacuous: every case changes exactly one
    // input and asserts the boolean actually flips). ----

    fn long() -> Duration {
        Duration::from_secs(60)
    }
    fn threshold() -> Duration {
        Duration::from_secs(30)
    }

    #[test]
    fn fires_when_everything_lines_up() {
        assert!(should_notify(true, false, true, long(), threshold()));
    }

    #[test]
    fn off_by_default_when_not_enabled() {
        // AC dev/02: off by default.
        assert!(!should_notify(false, false, true, long(), threshold()));
    }

    #[test]
    fn never_fires_for_machine_output_format() {
        // json/stream-json — a scripted/wrapper caller never gets notified.
        assert!(!should_notify(true, true, true, long(), threshold()));
    }

    #[test]
    fn never_fires_when_stderr_is_not_a_tty() {
        // The non-interactive/piped case — AC dev/02.
        assert!(!should_notify(true, false, false, long(), threshold()));
    }

    #[test]
    fn never_fires_under_the_threshold() {
        let short = Duration::from_secs(5);
        assert!(!should_notify(true, false, true, short, threshold()));
    }

    #[test]
    fn fires_exactly_at_the_threshold() {
        assert!(should_notify(true, false, true, threshold(), threshold()));
    }

    #[test]
    fn multiple_suppressors_still_suppress() {
        assert!(!should_notify(
            false,
            true,
            false,
            Duration::from_secs(1),
            threshold()
        ));
    }

    // ---- sanitize_summary / build_payload ----

    #[test]
    fn sanitize_strips_control_characters() {
        let evil = "hello\x1b]0;pwned\x07world";
        let clean = sanitize_summary(evil, 100);
        assert!(!clean.contains('\x1b'));
        assert!(!clean.contains('\x07'));
        assert_eq!(clean, "hello]0;pwnedworld");
    }

    #[test]
    fn sanitize_truncates_long_summaries() {
        let long_text = "x".repeat(200);
        let clean = sanitize_summary(&long_text, 10);
        assert_eq!(clean.chars().count(), 11); // 10 chars + the ellipsis.
        assert!(clean.ends_with(''));
    }

    #[test]
    fn sanitize_leaves_short_text_untouched() {
        assert_eq!(sanitize_summary("  hi there  ", 80), "hi there");
    }

    #[test]
    fn build_payload_includes_model_and_elapsed() {
        let (title, body) = build_payload("opus", Duration::from_secs(42), "done!");
        assert!(title.contains("supercode"));
        assert!(body.contains("opus"));
        assert!(body.contains("42s"));
        assert!(body.contains("done!"));
    }

    #[test]
    fn build_payload_never_leaks_more_than_a_safe_summary() {
        // A reply far longer than any real notification should carry gets
        // capped, not dumped whole into the body.
        let full_reply = "secret internal detail ".repeat(50);
        let (_, body) = build_payload("m", Duration::from_secs(1), &full_reply);
        assert!(body.len() < full_reply.len());
    }

    #[test]
    fn build_payload_omits_the_separator_for_an_empty_summary() {
        let (_, body) = build_payload("m", Duration::from_secs(3), "");
        assert_eq!(body, "m · 3s");
    }

    // ---- fire_desktop: absent-notifier degrades silently (no panic, no
    // hang) — the real "notify-send received the args" proof is the CLI
    // integration test (notify_cli.rs) with a fake script on PATH; this
    // just proves the no-op path never panics when nothing is on PATH at
    // all. ----

    #[test]
    fn fire_desktop_does_not_panic_when_notify_send_is_absent() {
        // Give PATH a value that plausibly has no `notify-send` on it.
        let old_path = std::env::var("PATH").ok();
        std::env::set_var("PATH", "/nonexistent-supercode-test-path");
        fire_desktop("title", "body");
        // fire_desktop only spawns a reap thread on SUCCESS, so there's
        // nothing to join here; reaching this line without panicking is
        // the assertion.
        if let Some(p) = old_path {
            std::env::set_var("PATH", p);
        }
    }

    #[test]
    fn ring_bell_does_not_panic() {
        ring_bell();
    }

    // ---- SMTP wire protocol: a fake TCP server plays SMTP server and
    // records exactly what the client sent, proving the conversation shape
    // (EHLO / MAIL FROM / RCPT TO / DATA / body / QUIT) end to end without
    // any real mail infrastructure. ----

    fn spawn_fake_smtp_server() -> (u16, std::sync::mpsc::Receiver<Vec<String>>) {
        use std::io::{BufRead, BufReader};
        use std::net::TcpListener;
        use std::sync::mpsc;

        let listener = TcpListener::bind("127.0.0.1:0").expect("bind fake SMTP server");
        let port = listener.local_addr().unwrap().port();
        let (tx, rx) = mpsc::channel();
        std::thread::spawn(move || {
            let (sock, _) = listener.accept().expect("accept one connection");
            let mut writer = sock.try_clone().expect("clone socket");
            let mut reader = BufReader::new(sock);
            let mut received = Vec::new();
            let mut in_data = false;

            let _ = write_line(&mut writer, "220 fake.smtp ready");
            loop {
                let mut line = String::new();
                let n = reader.read_line(&mut line).unwrap_or(0);
                if n == 0 {
                    break;
                }
                let trimmed = line.trim_end().to_string();
                let is_quit = trimmed.eq_ignore_ascii_case("QUIT");
                let is_data_end = trimmed == ".";
                received.push(trimmed.clone());
                if in_data && !is_data_end {
                    // SMTP DATA is one framed command: the server must not
                    // reply to individual headers or body lines.
                    continue;
                } else if is_quit {
                    let _ = write_line(&mut writer, "221 bye");
                    break;
                } else if trimmed.eq_ignore_ascii_case("DATA") {
                    in_data = true;
                    let _ = write_line(&mut writer, "354 go ahead");
                } else if is_data_end {
                    in_data = false;
                    let _ = write_line(&mut writer, "250 OK queued");
                } else {
                    let _ = write_line(&mut writer, "250 OK");
                }
            }
            let _ = tx.send(received);
        });
        (port, rx)
    }

    #[test]
    fn send_email_blocking_speaks_the_expected_smtp_conversation() {
        let (port, rx) = spawn_fake_smtp_server();
        let cfg = EmailConfig {
            smtp_host: "127.0.0.1".to_string(),
            smtp_port: port,
            from: "supercode@example.test".to_string(),
            to: "you@example.test".to_string(),
            username: None,
        };
        send_email_blocking(&cfg, "supercode: turn finished", "opus · 42s · done!")
            .expect("fake SMTP conversation should succeed");

        let received = rx
            .recv_timeout(Duration::from_secs(5))
            .expect("fake server should have recorded the conversation");
        assert!(received.iter().any(|l| l.starts_with("EHLO")));
        assert!(received
            .iter()
            .any(|l| l == "MAIL FROM:<supercode@example.test>"));
        assert!(received.iter().any(|l| l == "RCPT TO:<you@example.test>"));
        assert!(received.iter().any(|l| l == "DATA"));
        assert!(received
            .iter()
            .any(|l| l == "Subject: supercode: turn finished"));
        assert!(received.iter().any(|l| l.contains("opus · 42s · done!")));
        assert!(received.iter().any(|l| l == "."));
        assert!(received.iter().any(|l| l.eq_ignore_ascii_case("QUIT")));
    }

    #[test]
    fn send_email_blocking_sends_auth_login_when_username_configured() {
        let (port, rx) = spawn_fake_smtp_server();
        let cfg = EmailConfig {
            smtp_host: "127.0.0.1".to_string(),
            smtp_port: port,
            from: "supercode@example.test".to_string(),
            to: "you@example.test".to_string(),
            username: Some("bot".to_string()),
        };
        std::env::set_var("SUPERCODE_NOTIFY_EMAIL_PASSWORD", "s3cret");
        send_email_blocking(&cfg, "subject", "body").expect("auth conversation should succeed");
        std::env::remove_var("SUPERCODE_NOTIFY_EMAIL_PASSWORD");

        let received = rx.recv_timeout(Duration::from_secs(5)).expect("recorded");
        assert!(received.iter().any(|l| l == "AUTH LOGIN"));
        use base64::Engine;
        let b64 = base64::engine::general_purpose::STANDARD;
        assert!(received.iter().any(|l| l == &b64.encode("bot")));
        assert!(received.iter().any(|l| l == &b64.encode("s3cret")));
    }

    #[test]
    fn send_email_blocking_fails_cleanly_on_connection_refused() {
        // Nothing listening on this port (bind-then-drop to get a free
        // port that's guaranteed refused) — must return an Err, never
        // panic, so fire_email's swallow-the-error path has something
        // sane to swallow.
        let listener =
            std::net::TcpListener::bind("127.0.0.1:0").expect("bind to find a free port");
        let port = listener.local_addr().unwrap().port();
        drop(listener);

        let cfg = EmailConfig {
            smtp_host: "127.0.0.1".to_string(),
            smtp_port: port,
            from: "a@example.test".to_string(),
            to: "b@example.test".to_string(),
            username: None,
        };
        let result = send_email_blocking(&cfg, "s", "b");
        assert!(result.is_err());
    }

    // ---- maybe_fire: end-to-end dispatch decision, using a fake
    // notify-send on PATH so this test can observe whether the desktop
    // notification actually fired without touching a real display. ----

    #[test]
    fn maybe_fire_is_a_true_no_op_when_disabled() {
        // Point PATH somewhere with no notify-send; disabled settings must
        // never even attempt to look it up. If this panicked or hung, the
        // gating in maybe_fire would be broken.
        let settings = NotifySettings {
            enabled: false,
            threshold: Duration::from_secs(0),
            email: None,
            ..Default::default()
        };
        maybe_fire(&settings, false, true, Duration::from_secs(999), "m", "r");
    }

    #[test]
    fn maybe_fire_skips_machine_format_even_when_enabled() {
        let settings = NotifySettings {
            enabled: true,
            threshold: Duration::from_secs(0),
            email: None,
            ..Default::default()
        };
        // machine_format = true must suppress regardless of elapsed/threshold.
        maybe_fire(&settings, true, true, Duration::from_secs(999), "m", "r");
    }
}