edamame 0.1.1

A fast TUI Markdown editor and viewer
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
//! Terminal capability detection.
//!
//! Probes the terminal for features the editor uses: color depth, mouse
//! support, the image protocol supported
//! by the emulator (sixel / kitty / iterm2 / halfblocks), whether the locale
//! advertises full Unicode support, and whether the kitty keyboard
//! enhancement protocol is available.
//!
//! Detection uses three signals:
//!
//! * Environment variables (`$TERM`, `$COLORTERM`, `$TERM_PROGRAM`,
//!   `$KITTY_WINDOW_ID`, `$LC_ALL`, `$LANG`, etc.).
//! * Crossterm's `supports_keyboard_enhancement()` for keyboard protocol.
//! * `ratatui_image::picker::Picker::from_query_stdio` for image protocol.
//!
//! The `detect` function is designed to never panic and never block the UI
//! for noticeable time: all probes either complete in a few milliseconds or
//! gracefully fall back to a conservative default.

use std::env;

use ratatui_image::picker::{Picker, ProtocolType};

/// Color bit-depth supported by the terminal.
///
/// Values are ordered from poorest to richest so comparisons like
/// `depth >= ColorDepth::Ansi256` work as expected.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum ColorDepth {
    /// Terminal advertises no color support (e.g. `TERM=dumb`).  Rendering
    /// falls back to plain text with no ANSI style escapes.
    NoColor,
    /// Classic 8/16-color palette.
    Ansi16,
    /// 256-indexed color palette (xterm-256color and friends).
    Ansi256,
    /// 24-bit / true-color palette (`COLORTERM=truecolor` or `24bit`).
    TrueColor,
}

/// Image protocol supported by the terminal emulator.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ImageProtocol {
    /// DEC Sixel graphics (xterm with `--enable-sixel-graphics`, foot, wezterm).
    Sixel,
    /// Kitty graphics protocol (kitty, ghostty, wezterm).
    KittyGraphics,
    /// iTerm2 inline-images protocol.
    ITerm2,
    /// Unicode half-block fallback (works in any truecolor terminal).
    Halfblocks,
}

/// Detected terminal capabilities.
#[derive(Debug, Clone)]
pub struct Capabilities {
    /// Color bit-depth the terminal advertises.
    pub color_depth: ColorDepth,
    /// Whether the terminal appears to support mouse reporting.
    pub mouse: bool,
    /// Image protocol detected by `ratatui-image`, or `None` when image display
    /// is not supported.
    pub image_protocol: Option<ImageProtocol>,
    /// The `Picker` instance returned by `ratatui_image`'s startup probe.
    /// Retained so image rendering can reuse the already-probed
    /// configuration instead of re-running `Picker::from_query_stdio` on
    /// every cold image load.  `None` iff `image_protocol` is also `None`.
    pub image_picker: Option<Picker>,
    /// A second `Picker` forced to `ProtocolType::Halfblocks`, built from
    /// the same font-size reported by the native picker (no extra stdin
    /// probe).  Used by the halfblocks-fallback path: during
    /// partial visibility or active scrolling on non-Kitty terminals, we
    /// render via halfblocks (which is position-independent and cheap to
    /// cell-copy) and upgrade back to the native protocol once the image
    /// is fully visible and scroll has quiesced.  `None` iff image
    /// support is absent altogether.
    pub halfblocks_picker: Option<Picker>,
    /// Whether `$LC_ALL` / `$LC_CTYPE` / `$LANG` advertise a UTF-8 locale.
    /// Used as a proxy for "full Unicode support".
    pub unicode_full: bool,
    /// Whether the terminal answered `supports_keyboard_enhancement()`
    /// affirmatively.  When `true`, `Ctrl-Shift-Z` is usable as a secondary
    /// redo binding; when `false` the terminal is limited to the legacy
    /// control-byte encoding — it cannot represent shifted modifier
    /// combinations, nor `Ctrl` with a non-alphabetic key — and features
    /// that rely on them must gracefully degrade.
    pub keyboard_enhancement: bool,
}

impl Capabilities {
    /// Detect all capabilities.
    ///
    /// Must be called **after** the terminal has entered the alternate screen
    /// and raw mode, because `ratatui_image`'s Picker probes stdout/stdin
    /// with escape sequences.  The `kbd_enhancement` flag should be the
    /// result of the `supports_keyboard_enhancement()` query in `setup()` —
    /// we pass it in rather than re-querying here because both that query
    /// and the Picker probe read replies off the tty, and running them
    /// twice risks one consuming the other's response.
    pub fn detect(kbd_enhancement: bool) -> Self {
        let term = env::var("TERM").unwrap_or_default();
        let color_depth = detect_color_depth(&term);
        let mouse = detect_mouse(&term);
        let unicode_full = detect_unicode_full();
        let (image_protocol, image_picker) = detect_image_protocol();
        let halfblocks_picker = image_picker
            .as_ref()
            .map(|p| halfblocks_from(p.font_size()));

        Self {
            color_depth,
            mouse,
            image_protocol,
            image_picker,
            halfblocks_picker,
            unicode_full,
            keyboard_enhancement: kbd_enhancement,
        }
    }

    /// Probe the terminal's color depth from environment variables
    /// only — no escape-sequence I/O.  Safe to call before
    /// [`terminal::setup()`](fn@crate::terminal::setup) (and therefore before the full
    /// [`Self::detect`]), so the config loader can pick a
    /// capability-appropriate fallback theme when the active theme
    /// file is missing.  The full probe is the source of truth for
    /// every other consumer.
    pub fn detect_color_depth_from_env() -> ColorDepth {
        let term = env::var("TERM").unwrap_or_default();
        detect_color_depth(&term)
    }

    /// Detect everything that can be known from the environment alone —
    /// color depth, mouse, and locale — leaving the two probe-derived
    /// facts at their [`Self::minimal`] values (no image protocol, no
    /// keyboard enhancement).
    ///
    /// Used by `--doctor` when stdout or stdin is not a terminal.  The
    /// image and keyboard probes both write escape sequences and read
    /// the replies off the tty; with output redirected those sequences
    /// would land in the user's file and the probe would report "no
    /// support" for a terminal that has it.  Reporting the two facts as
    /// *unknown* is the honest answer, and the caller
    /// ([`crate::cli::doctor`]) prints them that way.
    pub fn env_only() -> Self {
        let term = env::var("TERM").unwrap_or_default();
        Self {
            color_depth: detect_color_depth(&term),
            mouse: detect_mouse(&term),
            unicode_full: detect_unicode_full(),
            ..Self::minimal()
        }
    }

    /// True iff the terminal advertises 24-bit color.  Anything below
    /// truecolor (256-indexed, 16-color, none) quantizes the RGB values
    /// every built-in theme and every rendered image is authored in, so
    /// this one predicate gates the theme picker, the image / diagram
    /// options in the welcome modal, and the first-run default theme.
    pub fn full_color(&self) -> bool {
        self.color_depth == ColorDepth::TrueColor
    }

    /// Conservative default used by tests and when probing is impossible.
    ///
    /// Assumes the minimum-common-denominator terminal: 16 colors, no mouse,
    /// no images, no kitty keyboard protocol.
    pub fn minimal() -> Self {
        Self {
            color_depth: ColorDepth::Ansi16,
            mouse: false,
            image_protocol: None,
            image_picker: None,
            halfblocks_picker: None,
            unicode_full: false,
            keyboard_enhancement: false,
        }
    }

    /// Build a stable, debuggable fingerprint that identifies this terminal
    /// "identity" for the new-terminal detection in the startup capabilities
    /// notice.  Combines `$TERM_PROGRAM` and `$TERM` (the env-level identity)
    /// with the detected capability tuple (so two environments that probe
    /// differently are treated as different terminals) and a `tmux` marker
    /// when running inside tmux.
    ///
    /// `$TERM_PROGRAM_VERSION` is deliberately excluded — every minor version
    /// update would otherwise re-trigger the notice.
    pub fn fingerprint(&self) -> String {
        let term_program = env::var("TERM_PROGRAM").unwrap_or_default();
        let term = env::var("TERM").unwrap_or_default();
        let tmux = if env::var("TMUX").is_ok() { "tmux" } else { "" };
        let color = match self.color_depth {
            ColorDepth::NoColor => "none",
            ColorDepth::Ansi16 => "16",
            ColorDepth::Ansi256 => "256",
            ColorDepth::TrueColor => "truecolor",
        };
        let image = match self.image_protocol {
            None => "none",
            Some(ImageProtocol::Sixel) => "sixel",
            Some(ImageProtocol::KittyGraphics) => "kitty",
            Some(ImageProtocol::ITerm2) => "iterm2",
            Some(ImageProtocol::Halfblocks) => "halfblocks",
        };
        format!(
            "{term_program}|{term}|{tmux}|{color}|{image}|mouse={}|kbd={}|unicode={}",
            self.mouse, self.keyboard_enhancement, self.unicode_full,
        )
    }
}

impl Default for Capabilities {
    fn default() -> Self {
        Self::minimal()
    }
}

// ── Probing helpers ──────────────────────────────────────────────────────────

/// Infer color depth from environment variables.
///
/// `$COLORTERM` takes precedence when it names a true-color terminal; failing
/// that we fall back to inspecting `$TERM` for the conventional `-256color`
/// suffix, then to the built-in 8/16-color palette.
fn detect_color_depth(term: &str) -> ColorDepth {
    if term == "dumb" || term.is_empty() {
        return ColorDepth::NoColor;
    }
    let colorterm = env::var("COLORTERM")
        .unwrap_or_default()
        .to_ascii_lowercase();
    if colorterm == "truecolor" || colorterm == "24bit" {
        return ColorDepth::TrueColor;
    }
    if term.contains("direct") {
        // e.g. `xterm-direct`, `tmux-direct`.
        return ColorDepth::TrueColor;
    }
    // A handful of modern terminals are known to support truecolor even when
    // `$COLORTERM` is unset (e.g. a remote session that stripped it).
    if env::var("KITTY_WINDOW_ID").is_ok() || env::var("WEZTERM_PANE").is_ok() {
        return ColorDepth::TrueColor;
    }
    if let Ok(tp) = env::var("TERM_PROGRAM") {
        match tp.as_str() {
            // Deliberately NOT `Apple_Terminal`: macOS Terminal.app tops out
            // at the 256-color palette — it silently quantizes 24-bit SGR
            // sequences, so claiming truecolor here would hand it themes and
            // images it renders wrong.  It falls through to the
            // `256color` check below.
            "iTerm.app" | "WezTerm" | "ghostty" | "Ghostty" => return ColorDepth::TrueColor,
            _ => {}
        }
    }
    if term.contains("256color") {
        return ColorDepth::Ansi256;
    }
    ColorDepth::Ansi16
}

/// Infer mouse support from `$TERM`.
///
/// Essentially every post-1990s xterm-compatible terminal supports xterm
/// mouse reporting.  The short list of exceptions is: `dumb`, empty, and
/// `linux` (the Linux framebuffer console has no mouse by default).
fn detect_mouse(term: &str) -> bool {
    if term == "dumb" || term == "linux" || term.is_empty() {
        return false;
    }
    true
}

/// True when the active locale advertises UTF-8.
fn detect_unicode_full() -> bool {
    for var in ["LC_ALL", "LC_CTYPE", "LANG"] {
        if let Ok(v) = env::var(var) {
            let upper = v.to_ascii_uppercase();
            if upper.contains("UTF-8") || upper.contains("UTF8") {
                return true;
            }
        }
    }
    false
}

/// Build a picker that is **guaranteed** to encode halfblocks, at the
/// terminal's real `font_size`.
///
/// Neither of ratatui-image's two constructors does this on its own:
///
/// * `Picker::halfblocks()` forces the protocol but hardcodes
///   `font_size` to (10, 20), which is wrong for any terminal whose
///   cells aren't 10×20 px — the halfblocks encoding would then use a
///   different pixel-to-cell aspect ratio than the native protocol, and
///   an image would change shape every time it crossed the
///   native↔halfblocks boundary during scroll.
/// * `Picker::from_fontsize()` keeps the font size but *infers a
///   protocol from the environment*: `iterm2_from_env()` returns
///   `Iterm2` whenever `$TERM_PROGRAM` names iTerm2, WezTerm, VS Code,
///   Warp, Hyper, Tabby, rio, mintty or Bobcat (or `$LC_TERMINAL` names
///   iTerm2, or we're in tmux under one of those).  On every one of
///   those terminals the "halfblocks" picker silently produced an
///   **iTerm2** picker instead, so the pre-rendered scratch buffer that
///   `image::render_halfblocks_scratch` builds held a single cell
///   carrying a base64 PNG escape sequence plus a field of `skip` cells,
///   rather than position-independent halfblock cells.  That broke the
///   entire partial-render fallback: `paint_halfblocks_partial` copies
///   cells by row, so the image appeared only when the escape cell at
///   row 0 happened to be copied (a full-fidelity flash) and vanished as
///   soon as the top row scrolled off, and each flash re-transmitted the
///   whole PNG to the terminal — the scroll stutter.
///
/// So: take the font size from one and stamp the protocol from the
/// other.
fn halfblocks_from(font_size: ratatui_image::FontSize) -> Picker {
    // `from_fontsize` is deprecated in ratatui-image 9+, but it is the
    // only constructor that accepts a probed font size.
    #[allow(deprecated)]
    let mut picker = Picker::from_fontsize(font_size);
    picker.set_protocol_type(ProtocolType::Halfblocks);
    picker
}

/// True when we are (directly or over ssh) talking to iTerm2.app.
///
/// `$LC_TERMINAL` is iTerm2's own forwarded marker, so it stays correct
/// across ssh — and in that case the terminal on the far end of the pipe
/// really is iTerm2, which is what matters for protocol selection.
fn is_iterm2_app() -> bool {
    env::var("TERM_PROGRAM").is_ok_and(|v| v.contains("iTerm"))
        || env::var("LC_TERMINAL").is_ok_and(|v| v.contains("iTerm"))
}

/// Whether the iTerm2 env hint is trustworthy enough to override an
/// affirmative Kitty capability probe (see [`resolve_protocol`]).
///
/// Under tmux it is not.  tmux's default `update-environment` covers
/// neither `TERM_PROGRAM` nor `LC_TERMINAL`, so a pane keeps whatever
/// the client that *created the server* exported: start tmux in iTerm2,
/// detach, reattach from Ghostty or kitty, and `$LC_TERMINAL` still
/// reads `iTerm2` while the terminal actually on the other end of the
/// pipe speaks Kitty and not iTerm2 at all.  Pinning `Iterm2` there
/// would break images on a terminal that had them working.
///
/// The stdio capability probe has no such staleness problem — it asks
/// the live terminal, through tmux passthrough — which is exactly why
/// ratatui-image treats it as authoritative over env hints.  So inside
/// tmux we defer to it and leave the probe's answer alone.  The common
/// case this gives up is tmux running *inside* iTerm2, where the probe
/// says Kitty and we now believe it; that costs blank image rows, which
/// is the same outcome the user already had before this override
/// existed, and is recoverable by the halfblocks fallback in a way that
/// a wrong-protocol pin on Ghostty is not.
fn iterm2_hint_is_trustworthy() -> bool {
    is_iterm2_app() && env::var_os("TMUX").is_none()
}

/// Resolve the protocol edamame will actually encode with from the one
/// `Picker::from_query_stdio` probed.
///
/// iTerm2 3.5+ answers the Kitty graphics capability query
/// (`ESC _Gi=31,…,a=q`) affirmatively, and ratatui-image treats that I/O
/// probe as authoritative over its `$TERM_PROGRAM` hint — so in iTerm2
/// the picker comes back as `Kitty`.  But ratatui-image's Kitty backend
/// renders exclusively through the protocol's **unicode-placeholder**
/// extension (transmit once with `U=1`, then paint U+10EEEE cells
/// carrying the image id in diacritics), and that extension is one of
/// the parts iTerm2 does *not* implement.  The image is transmitted and
/// then never placed: the reserved rows stay blank.  ratatui-image's own
/// compatibility matrix lists iTerm2's supported protocol as `iTerm2`,
/// so pin it there.
///
/// Only `Kitty` is overridden — a probe that lands on Sixel or
/// Halfblocks is left alone.  `iterm2` should come from
/// [`iterm2_hint_is_trustworthy`], not `is_iterm2_app` directly.
fn resolve_protocol(probed: ProtocolType, iterm2: bool) -> ProtocolType {
    match probed {
        ProtocolType::Kitty if iterm2 => ProtocolType::Iterm2,
        other => other,
    }
}

/// Ask `ratatui_image` to probe for an image protocol.  Returns the detected
/// protocol and the `Picker` instance; the Picker is retained and
/// passed through to the image-rendering layer so cold image loads reuse
/// the already-probed configuration.
///
/// Halfblocks are reported as `Some(ImageProtocol::Halfblocks)` — they are
/// still a usable protocol, just lower-fidelity than sixel/kitty/iterm2.
fn detect_image_protocol() -> (Option<ImageProtocol>, Option<Picker>) {
    // Picker::from_query_stdio may write escape sequences; a panic here would
    // be disastrous (corrupted terminal state), so we catch-and-swallow.
    let result = std::panic::catch_unwind(Picker::from_query_stdio);
    let mut picker = match result {
        Ok(Ok(p)) => p,
        _ => return (None, None),
    };

    picker.set_protocol_type(resolve_protocol(
        picker.protocol_type(),
        iterm2_hint_is_trustworthy(),
    ));

    let protocol = match picker.protocol_type() {
        ProtocolType::Sixel => ImageProtocol::Sixel,
        ProtocolType::Kitty => ImageProtocol::KittyGraphics,
        ProtocolType::Iterm2 => ImageProtocol::ITerm2,
        ProtocolType::Halfblocks => ImageProtocol::Halfblocks,
    };
    (Some(protocol), Some(picker))
}

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

    // `EnvGuard` (save / set / restore-on-drop) and `env_lock` used to
    // live here.  They moved to `crate::test_env` when a second module
    // grew env-mutating tests: a lock private to this module cannot
    // exclude `config::config`'s `XDG_CONFIG_HOME` writes or
    // `cli::doctor`'s reads of the very variables set below, and the
    // race those guard against is process-wide.
    use crate::test_env::{env_lock, EnvGuard};

    // ── Image protocol ────────────────────────────────────────────────

    /// The bug this pins: `Picker::from_fontsize` infers its protocol
    /// from `$TERM_PROGRAM`, so on iTerm2 (and WezTerm / VS Code / Warp
    /// / Hyper / Tabby / rio / mintty / Bobcat) the "halfblocks" picker
    /// came back as an **iTerm2** picker.  Every scratch buffer built
    /// from it held a base64 PNG escape instead of halfblock cells,
    /// which the row-clipping partial painter cannot slice.
    #[test]
    fn halfblocks_picker_is_halfblocks_even_under_iterm2() {
        let _lock = env_lock();
        let _g1 = EnvGuard::set("TERM_PROGRAM", "iTerm.app");
        let _g2 = EnvGuard::unset("TMUX");
        let picker = halfblocks_from(ratatui_image::FontSize::new(7, 15));
        assert_eq!(picker.protocol_type(), ProtocolType::Halfblocks);
    }

    /// The probed font size must survive — `Picker::halfblocks()` would
    /// hardcode (10, 20) and change the image's aspect ratio each time
    /// it crossed the native↔halfblocks boundary.
    #[test]
    fn halfblocks_picker_keeps_the_probed_font_size() {
        let _lock = env_lock();
        let _g = EnvGuard::unset("TERM_PROGRAM");
        let picker = halfblocks_from(ratatui_image::FontSize::new(7, 15));
        assert_eq!(picker.font_size().width, 7);
        assert_eq!(picker.font_size().height, 15);
    }

    #[test]
    fn iterm2_app_detected_from_term_program_and_lc_terminal() {
        let _lock = env_lock();
        {
            let _g1 = EnvGuard::set("TERM_PROGRAM", "iTerm.app");
            let _g2 = EnvGuard::unset("LC_TERMINAL");
            assert!(is_iterm2_app());
        }
        {
            // ssh'd out of iTerm2: only the forwarded marker survives.
            let _g1 = EnvGuard::unset("TERM_PROGRAM");
            let _g2 = EnvGuard::set("LC_TERMINAL", "iTerm2");
            assert!(is_iterm2_app());
        }
        {
            let _g1 = EnvGuard::set("TERM_PROGRAM", "ghostty");
            let _g2 = EnvGuard::unset("LC_TERMINAL");
            assert!(!is_iterm2_app());
        }
    }

    /// The headline override: iTerm2 answers the Kitty capability query
    /// but can't place images via unicode placeholders, so a `Kitty`
    /// probe under iTerm2 must be pinned to `Iterm2` or the reserved
    /// rows stay blank.
    #[test]
    fn kitty_probe_under_iterm2_is_pinned_to_iterm2() {
        assert_eq!(
            resolve_protocol(ProtocolType::Kitty, true),
            ProtocolType::Iterm2
        );
    }

    /// Only `Kitty` is overridden.  A terminal that probed Sixel or
    /// Halfblocks is answering about a protocol iTerm2's Kitty quirk
    /// says nothing about, and a real Kitty-family terminal (no iTerm2
    /// hint) must keep its native protocol.
    #[test]
    fn resolve_protocol_leaves_every_other_probe_alone() {
        for probed in [
            ProtocolType::Kitty,
            ProtocolType::Sixel,
            ProtocolType::Iterm2,
            ProtocolType::Halfblocks,
        ] {
            assert_eq!(
                resolve_protocol(probed, false),
                probed,
                "{probed:?} must survive without an iTerm2 hint"
            );
        }
        for probed in [
            ProtocolType::Sixel,
            ProtocolType::Iterm2,
            ProtocolType::Halfblocks,
        ] {
            assert_eq!(
                resolve_protocol(probed, true),
                probed,
                "{probed:?} must survive even under iTerm2"
            );
        }
    }

    /// Inside tmux the iTerm2 env hint is untrustworthy: `TERM_PROGRAM`
    /// and `LC_TERMINAL` are not in tmux's default `update-environment`,
    /// so a session created from iTerm2 and reattached from Ghostty
    /// still advertises iTerm2 while the live terminal speaks Kitty.
    /// The stdio capability probe has no such staleness, so we defer to
    /// it rather than pin a protocol Ghostty cannot render.
    #[test]
    fn iterm2_hint_is_distrusted_inside_tmux() {
        let _lock = env_lock();
        let _g1 = EnvGuard::set("LC_TERMINAL", "iTerm2");
        let _g2 = EnvGuard::unset("TERM_PROGRAM");
        {
            let _g3 = EnvGuard::unset("TMUX");
            assert!(iterm2_hint_is_trustworthy(), "bare iTerm2 is trusted");
        }
        {
            let _g3 = EnvGuard::set("TMUX", "/tmp/tmux-501/default,1234,0");
            assert!(
                !iterm2_hint_is_trustworthy(),
                "a stale forwarded marker inside tmux must not pin Iterm2"
            );
            assert_eq!(
                resolve_protocol(ProtocolType::Kitty, iterm2_hint_is_trustworthy()),
                ProtocolType::Kitty,
                "the live capability probe wins inside tmux"
            );
        }
    }

    /// A non-iTerm2 terminal outside tmux is trivially untrusted for the
    /// pin — the guard must gate on the hint, not merely on tmux.
    #[test]
    fn iterm2_hint_is_absent_without_an_iterm2_marker() {
        let _lock = env_lock();
        let _g1 = EnvGuard::set("TERM_PROGRAM", "ghostty");
        let _g2 = EnvGuard::unset("LC_TERMINAL");
        let _g3 = EnvGuard::unset("TMUX");
        assert!(!iterm2_hint_is_trustworthy());
    }

    #[test]
    fn color_depth_no_color_for_dumb_terminal() {
        assert_eq!(detect_color_depth("dumb"), ColorDepth::NoColor);
        assert_eq!(detect_color_depth(""), ColorDepth::NoColor);
    }

    #[test]
    fn color_depth_truecolor_from_colorterm() {
        let _lock = env_lock();
        let _g1 = EnvGuard::set("COLORTERM", "truecolor");
        let _g2 = EnvGuard::unset("KITTY_WINDOW_ID");
        let _g3 = EnvGuard::unset("WEZTERM_PANE");
        let _g4 = EnvGuard::unset("TERM_PROGRAM");
        assert_eq!(detect_color_depth("xterm-256color"), ColorDepth::TrueColor);
    }

    #[test]
    fn color_depth_256_from_term_suffix() {
        let _lock = env_lock();
        let _g1 = EnvGuard::unset("COLORTERM");
        let _g2 = EnvGuard::unset("KITTY_WINDOW_ID");
        let _g3 = EnvGuard::unset("WEZTERM_PANE");
        let _g4 = EnvGuard::unset("TERM_PROGRAM");
        assert_eq!(detect_color_depth("xterm-256color"), ColorDepth::Ansi256);
    }

    #[test]
    fn color_depth_16_for_plain_xterm() {
        let _lock = env_lock();
        let _g1 = EnvGuard::unset("COLORTERM");
        let _g2 = EnvGuard::unset("KITTY_WINDOW_ID");
        let _g3 = EnvGuard::unset("WEZTERM_PANE");
        let _g4 = EnvGuard::unset("TERM_PROGRAM");
        assert_eq!(detect_color_depth("xterm"), ColorDepth::Ansi16);
    }

    #[test]
    fn color_depth_truecolor_for_kitty_envvar() {
        let _lock = env_lock();
        let _g1 = EnvGuard::unset("COLORTERM");
        let _g2 = EnvGuard::set("KITTY_WINDOW_ID", "1");
        let _g3 = EnvGuard::unset("WEZTERM_PANE");
        let _g4 = EnvGuard::unset("TERM_PROGRAM");
        assert_eq!(detect_color_depth("xterm"), ColorDepth::TrueColor);
    }

    #[test]
    fn color_depth_256_for_apple_terminal() {
        // Terminal.app reports `TERM_PROGRAM=Apple_Terminal` with
        // `TERM=xterm-256color` and no `COLORTERM`.  It must resolve to
        // Ansi256 — it quantizes 24-bit SGR sequences, so treating it as
        // truecolor mis-renders every theme and image.
        let _lock = env_lock();
        let _g1 = EnvGuard::unset("COLORTERM");
        let _g2 = EnvGuard::unset("KITTY_WINDOW_ID");
        let _g3 = EnvGuard::unset("WEZTERM_PANE");
        let _g4 = EnvGuard::set("TERM_PROGRAM", "Apple_Terminal");
        assert_eq!(detect_color_depth("xterm-256color"), ColorDepth::Ansi256);
    }

    #[test]
    fn full_color_only_for_truecolor() {
        let caps = Capabilities {
            color_depth: ColorDepth::TrueColor,
            ..Capabilities::minimal()
        };
        assert!(caps.full_color());
        for depth in [ColorDepth::Ansi256, ColorDepth::Ansi16, ColorDepth::NoColor] {
            let caps = Capabilities {
                color_depth: depth,
                ..Capabilities::minimal()
            };
            assert!(!caps.full_color(), "{depth:?} is not full color");
        }
    }

    #[test]
    fn mouse_false_for_dumb_and_linux() {
        assert!(!detect_mouse("dumb"));
        assert!(!detect_mouse("linux"));
        assert!(!detect_mouse(""));
    }

    #[test]
    fn mouse_true_for_modern_terminals() {
        assert!(detect_mouse("xterm-256color"));
        assert!(detect_mouse("alacritty"));
        assert!(detect_mouse("tmux-256color"));
    }

    #[test]
    fn unicode_full_from_lang() {
        let _lock = env_lock();
        let _g1 = EnvGuard::set("LANG", "en_US.UTF-8");
        let _g2 = EnvGuard::unset("LC_ALL");
        let _g3 = EnvGuard::unset("LC_CTYPE");
        assert!(detect_unicode_full());
    }

    #[test]
    fn unicode_false_for_c_locale() {
        let _lock = env_lock();
        let _g1 = EnvGuard::set("LANG", "C");
        let _g2 = EnvGuard::unset("LC_ALL");
        let _g3 = EnvGuard::unset("LC_CTYPE");
        assert!(!detect_unicode_full());
    }

    #[test]
    fn minimal_capabilities_are_conservative() {
        let caps = Capabilities::minimal();
        assert_eq!(caps.color_depth, ColorDepth::Ansi16);
        assert!(!caps.mouse);
        assert!(caps.image_protocol.is_none());
        assert!(!caps.unicode_full);
        assert!(!caps.keyboard_enhancement);
    }

    #[test]
    fn fingerprint_is_stable_for_identical_caps() {
        let _lock = env_lock();
        let _g1 = EnvGuard::set("TERM_PROGRAM", "WezTerm");
        let _g2 = EnvGuard::set("TERM", "xterm-256color");
        let _g3 = EnvGuard::unset("TMUX");
        let caps = Capabilities {
            color_depth: ColorDepth::TrueColor,
            mouse: true,
            image_protocol: Some(ImageProtocol::KittyGraphics),
            image_picker: None,
            halfblocks_picker: None,
            unicode_full: true,
            keyboard_enhancement: true,
        };
        assert_eq!(caps.fingerprint(), caps.fingerprint());
    }

    #[test]
    fn fingerprint_differs_when_a_capability_flips() {
        let _lock = env_lock();
        let _g1 = EnvGuard::set("TERM_PROGRAM", "WezTerm");
        let _g2 = EnvGuard::set("TERM", "xterm-256color");
        let _g3 = EnvGuard::unset("TMUX");
        let base = Capabilities {
            color_depth: ColorDepth::TrueColor,
            mouse: true,
            image_protocol: Some(ImageProtocol::KittyGraphics),
            image_picker: None,
            halfblocks_picker: None,
            unicode_full: true,
            keyboard_enhancement: true,
        };
        let mouseless = Capabilities {
            mouse: false,
            ..base.clone()
        };
        let no_kbd = Capabilities {
            keyboard_enhancement: false,
            ..base.clone()
        };
        let no_image = Capabilities {
            image_protocol: None,
            ..base.clone()
        };
        assert_ne!(base.fingerprint(), mouseless.fingerprint());
        assert_ne!(base.fingerprint(), no_kbd.fingerprint());
        assert_ne!(base.fingerprint(), no_image.fingerprint());
    }

    #[test]
    fn fingerprint_includes_tmux_marker() {
        let _lock = env_lock();
        let _g1 = EnvGuard::set("TERM_PROGRAM", "WezTerm");
        let _g2 = EnvGuard::set("TERM", "tmux-256color");
        let caps = Capabilities::minimal();
        let _no_tmux = EnvGuard::unset("TMUX");
        let outside = caps.fingerprint();
        let _in_tmux = EnvGuard::set("TMUX", "/tmp/tmux-1000/default,123,0");
        let inside = caps.fingerprint();
        assert_ne!(outside, inside);
        assert!(inside.contains("tmux"));
    }
}