omni-dev 0.41.0

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

use std::fs;
use std::io::Write;

use anyhow::{Context, Result};
use clap::{Parser, ValueEnum};

use crate::cli::gmail::format::{output_as, sanitize_for_terminal, OutputFormat};
use crate::gmail::client::GmailClient;
use crate::gmail::messages_api::{MessageFormat, MessagesApi};
use crate::gmail::raw_message::decode_raw_message;
use crate::gmail::render::render_markdown;
use crate::gmail::types::Message;

/// How much of the message to fetch.
///
/// Named `--detail`, not `--format`: ADR-0046 retired `--format` project-wide
/// (every surviving `--format` in the codebase is a hidden deprecated alias
/// for `-o/--output`), so a new *visible* `--format` would be the only one
/// left and would collide in spirit with that migration — Gmail's `format`
/// is a request-side projection, not an output format, which is a different
/// axis from `-o` entirely (the same reasoning ADR-0046 applies to
/// `--out-file`). Variant names match Gmail's own wire values verbatim
/// (`minimal`/`metadata`/`full`/`raw`) rather than an invented shorthand.
#[derive(Clone, Copy, Debug, Default, ValueEnum)]
pub enum ReadDetail {
    /// Only `id`/`threadId`/`labelIds`/`sizeEstimate` — no headers or body.
    Minimal,
    /// Headers and snippet only, no body.
    Metadata,
    /// The full parsed MIME structure. Default.
    #[default]
    Full,
    /// The full RFC 2822 message, base64url-encoded.
    Raw,
}

impl ReadDetail {
    fn as_message_format(self) -> MessageFormat {
        match self {
            Self::Minimal => MessageFormat::Minimal,
            Self::Metadata => MessageFormat::Metadata,
            Self::Full => MessageFormat::Full,
            Self::Raw => MessageFormat::Raw,
        }
    }
}

/// Output format for `gmail read`, extending the shared [`OutputFormat`]
/// with `Markdown` — a human-readable rendering of the message headers
/// (RFC 2047-decoded) and body via
/// [`render_markdown`](crate::gmail::render::render_markdown), the same
/// function `gmail render` uses for archived `.eml` files (#1513). Kept
/// local to `read` rather than added to the shared `OutputFormat` used
/// crate-wide: every other CLI surface's `-o` renders arbitrary
/// `Serialize` data generically, and a `Markdown` variant only makes sense
/// for a MIME message.
#[derive(Clone, Debug, Default, ValueEnum)]
pub enum ReadOutputFormat {
    /// Human-readable table (id/thread-id/labels/snippet). Default.
    #[default]
    Table,
    /// JSON.
    Json,
    /// YAML (single document).
    Yaml,
    /// YAML stream (`---`-separated multi-document).
    Yamls,
    /// JSON Lines.
    Jsonl,
    /// Human-readable Markdown rendering of the full message (headers +
    /// body). Always fetches the complete raw MIME message regardless of
    /// `--detail`, since rendering needs the full message structure.
    Markdown,
}

impl ReadOutputFormat {
    /// Converts to the shared [`OutputFormat`] for the non-`Markdown`
    /// variants. Never called for `Markdown`, which `run_read` handles
    /// before this conversion is needed.
    fn as_shared(&self) -> OutputFormat {
        match self {
            Self::Table => OutputFormat::Table,
            Self::Json => OutputFormat::Json,
            Self::Yaml => OutputFormat::Yaml,
            Self::Yamls => OutputFormat::Yamls,
            Self::Jsonl => OutputFormat::Jsonl,
            Self::Markdown => unreachable!("Markdown is handled before this point in run_read"),
        }
    }
}

/// Reads a single Gmail message.
///
/// (mirrors the `gmail_message_read` MCP tool)
#[derive(Parser)]
pub struct ReadCommand {
    /// Gmail message id.
    pub message_id: String,

    /// Output file (writes to stdout if omitted).
    #[arg(long = "out-file", value_name = "PATH")]
    pub out_file: Option<String>,

    /// How much of the message to fetch.
    #[arg(long, value_enum, default_value_t = ReadDetail::Full)]
    pub detail: ReadDetail,

    /// Output format.
    #[arg(short = 'o', long, value_enum, default_value_t = ReadOutputFormat::Table)]
    pub output: ReadOutputFormat,

    /// Collapses `>`-quoted reply history nested more than one level deep
    /// into a one-line `*(N quoted lines omitted)*` marker (#1514). Only
    /// affects `-o markdown`, mirroring `--detail`'s reverse asymmetry (it
    /// is silently ignored elsewhere). Off by default: verbatim rendering
    /// is fully information-preserving, and the full text is one re-render
    /// away without this flag.
    #[arg(long)]
    pub fold_quotes: bool,
}

impl ReadCommand {
    /// Runs the command against the shared client resolved by the parent
    /// `GmailCommand::execute`.
    pub async fn execute(self, client: &GmailClient) -> Result<()> {
        run_read(
            client,
            &self.message_id,
            self.detail,
            self.out_file.as_deref(),
            &self.output,
            self.fold_quotes,
        )
        .await
    }
}

/// Fetches the message and emits it in the requested format.
///
/// Split from [`ReadCommand::execute`] so tests can inject a wiremock
/// client without going through the credential-loading path.
async fn run_read(
    client: &GmailClient,
    message_id: &str,
    detail: ReadDetail,
    out_file: Option<&str>,
    output: &ReadOutputFormat,
    fold_quotes: bool,
) -> Result<()> {
    if matches!(output, ReadOutputFormat::Markdown) {
        // Rendering needs the full raw MIME message regardless of
        // `--detail`, so this fetches with `format=raw` directly rather
        // than honouring `detail.as_message_format()`.
        let message = MessagesApi::new(client)
            .get(message_id, MessageFormat::Raw, &[])
            .await?;
        let bytes = decode_raw_message(&message)?;
        let markdown = render_markdown(&bytes, fold_quotes);

        if let Some(path) = out_file {
            fs::write(path, &markdown).with_context(|| format!("Failed to write to {path}"))?;
            println!("Saved to: {path}");
            return Ok(());
        }
        print!("{markdown}");
        return Ok(());
    }

    let message = MessagesApi::new(client)
        .get(message_id, detail.as_message_format(), &[])
        .await?;

    if let Some(path) = out_file {
        if matches!(detail, ReadDetail::Raw) {
            let bytes = decode_raw_message(&message)?;
            fs::write(path, &bytes).with_context(|| format!("Failed to write to {path}"))?;
        } else {
            let rendered = render_plain_text(&message);
            fs::write(path, &rendered).with_context(|| format!("Failed to write to {path}"))?;
        }
        println!("Saved to: {path}");
        return Ok(());
    }

    if output_as(&message, &output.as_shared())? {
        return Ok(());
    }
    let stdout = std::io::stdout();
    let mut handle = stdout.lock();
    render_read_table(&message, &mut handle)
}

/// Renders a message as a flat `key: value` header block followed by its
/// snippet — an `.eml`-ish preview for `--out-file` on non-`raw` details,
/// not a markdown dialect. `--detail raw` never reaches this: it writes the
/// decoded bytes from [`decode_raw_message`] instead, since Gmail's `raw`
/// field only comes back populated for that format.
fn render_plain_text(message: &Message) -> String {
    let mut lines = Vec::new();
    lines.push(format!("Id: {}", message.id));
    if let Some(thread_id) = &message.thread_id {
        lines.push(format!("Thread-Id: {thread_id}"));
    }
    if !message.label_ids.is_empty() {
        lines.push(format!("Labels: {}", message.label_ids.join(", ")));
    }
    lines.push(String::new());
    if let Some(snippet) = &message.snippet {
        lines.push(snippet.clone());
    }
    lines.join("\n")
}

/// Renders a single message as a bespoke header block — a "table" in the
/// sense of "one command, one rendering," not a literal grid, matching the
/// Datadog `monitor get` precedent for single-record views.
fn render_read_table(message: &Message, out: &mut dyn Write) -> Result<()> {
    writeln!(out, "Id: {}", sanitize_for_terminal(&message.id))
        .context("Failed to write read row")?;
    if let Some(thread_id) = &message.thread_id {
        writeln!(out, "Thread-Id: {}", sanitize_for_terminal(thread_id))
            .context("Failed to write read row")?;
    }
    if !message.label_ids.is_empty() {
        let labels = message
            .label_ids
            .iter()
            .map(|l| sanitize_for_terminal(l))
            .collect::<Vec<_>>()
            .join(", ");
        writeln!(out, "Labels: {labels}").context("Failed to write read row")?;
    }
    if let Some(snippet) = &message.snippet {
        writeln!(out, "Snippet: {}", sanitize_for_terminal(snippet))
            .context("Failed to write read row")?;
    }
    Ok(())
}

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used)]
mod tests {
    use super::*;
    use crate::gmail::auth::{GmailCredentials, GmailScope};
    use crate::utils::secret::Secret;
    use base64::Engine as _;

    fn test_credentials() -> GmailCredentials {
        GmailCredentials {
            client_id: "client-1".to_string(),
            client_secret: Secret::new("secret-1"),
            refresh_token: Secret::new("refresh-1"),
            scope: GmailScope::ReadOnly,
        }
    }

    async fn client_with_bootstrapped_token(server: &wiremock::MockServer) -> GmailClient {
        wiremock::Mock::given(wiremock::matchers::method("POST"))
            .and(wiremock::matchers::path("/token"))
            .respond_with(
                wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({
                    "access_token": "test-token",
                    "expires_in": 3600,
                })),
            )
            .mount(server)
            .await;

        let mut client = GmailClient::new(&server.uri(), &test_credentials()).unwrap();
        crate::gmail::client::test_support::replace_session(
            &mut client,
            &test_credentials(),
            &format!("{}/token", server.uri()),
        );
        client
    }

    #[test]
    fn read_detail_maps_to_message_format() {
        assert!(matches!(
            ReadDetail::Minimal.as_message_format(),
            MessageFormat::Minimal
        ));
        assert!(matches!(
            ReadDetail::Metadata.as_message_format(),
            MessageFormat::Metadata
        ));
        assert!(matches!(
            ReadDetail::Full.as_message_format(),
            MessageFormat::Full
        ));
        assert!(matches!(
            ReadDetail::Raw.as_message_format(),
            MessageFormat::Raw
        ));
    }

    #[test]
    fn render_plain_text_includes_id_labels_and_snippet() {
        let message = Message {
            id: "m1".to_string(),
            thread_id: Some("t1".to_string()),
            label_ids: vec!["INBOX".to_string(), "UNREAD".to_string()],
            snippet: Some("Hi there".to_string()),
            ..Default::default()
        };
        let text = render_plain_text(&message);
        assert!(text.contains("Id: m1"));
        assert!(text.contains("Thread-Id: t1"));
        assert!(text.contains("Labels: INBOX, UNREAD"));
        assert!(text.contains("Hi there"));
    }

    // ── render_read_table ────────────────────────────────────────────

    #[test]
    fn render_read_table_writes_id_thread_labels_and_snippet() {
        let message = Message {
            id: "m1".to_string(),
            thread_id: Some("t1".to_string()),
            label_ids: vec!["INBOX".to_string(), "UNREAD".to_string()],
            snippet: Some("Hi there".to_string()),
            ..Default::default()
        };
        let mut buf = Vec::new();
        render_read_table(&message, &mut buf).unwrap();
        let text = String::from_utf8(buf).unwrap();
        assert!(text.contains("Id: m1"));
        assert!(text.contains("Thread-Id: t1"));
        assert!(text.contains("Labels: INBOX, UNREAD"));
        assert!(text.contains("Snippet: Hi there"));
    }

    #[test]
    fn render_read_table_omits_absent_fields() {
        let message = Message {
            id: "m1".to_string(),
            ..Default::default()
        };
        let mut buf = Vec::new();
        render_read_table(&message, &mut buf).unwrap();
        let text = String::from_utf8(buf).unwrap();
        assert_eq!(text, "Id: m1\n");
    }

    #[test]
    fn render_read_table_strips_control_bytes_from_server_strings() {
        let message = Message {
            id: "m1".to_string(),
            thread_id: Some("t\x1b[31m1".to_string()),
            label_ids: vec!["IN\rBOX".to_string()],
            snippet: Some("evil\x07snippet\u{9b}2J".to_string()),
            ..Default::default()
        };
        let mut buf = Vec::new();
        render_read_table(&message, &mut buf).unwrap();
        let text = String::from_utf8(buf).unwrap();
        assert!(
            !text.contains(|c: char| c.is_control() && c != '\n'),
            "{text:?}"
        );
        assert!(text.contains("Snippet: evilsnippet2J"), "{text:?}");
    }

    // ── run_read ─────────────────────────────────────────────────────

    #[tokio::test]
    async fn run_read_writes_to_out_file() {
        let server = wiremock::MockServer::start().await;
        let client = client_with_bootstrapped_token(&server).await;
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path("/gmail/v1/users/me/messages/m1"))
            .respond_with(
                wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({
                    "id": "m1",
                    "snippet": "Hi there",
                })),
            )
            .mount(&server)
            .await;

        let temp_dir = tempfile::tempdir().unwrap();
        let path = temp_dir.path().join("message.txt");
        run_read(
            &client,
            "m1",
            ReadDetail::Full,
            Some(path.to_str().unwrap()),
            &ReadOutputFormat::Table,
            false,
        )
        .await
        .unwrap();

        let content = fs::read_to_string(&path).unwrap();
        assert!(content.contains("Hi there"));
    }

    #[tokio::test]
    async fn run_read_detail_raw_out_file_writes_decoded_bytes_not_base64() {
        let server = wiremock::MockServer::start().await;
        let client = client_with_bootstrapped_token(&server).await;
        let source = "From: a@example.com\r\nSubject: Hi\r\n\r\nBody text.";
        let encoded = base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(source);
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path("/gmail/v1/users/me/messages/m1"))
            .and(wiremock::matchers::query_param("format", "raw"))
            .respond_with(
                wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({
                    "id": "m1",
                    "raw": encoded,
                })),
            )
            .mount(&server)
            .await;

        let temp_dir = tempfile::tempdir().unwrap();
        let path = temp_dir.path().join("message.eml");
        run_read(
            &client,
            "m1",
            ReadDetail::Raw,
            Some(path.to_str().unwrap()),
            &ReadOutputFormat::Table,
            false,
        )
        .await
        .unwrap();

        // A genuine byte-exact copy: no Id:/Thread-Id:/Labels: preamble, no
        // duplicated snippet, and definitely not still base64-encoded.
        let bytes = fs::read(&path).unwrap();
        assert_eq!(bytes, source.as_bytes());
    }

    #[tokio::test]
    async fn run_read_detail_raw_out_file_propagates_decode_errors() {
        let server = wiremock::MockServer::start().await;
        let client = client_with_bootstrapped_token(&server).await;
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path("/gmail/v1/users/me/messages/m1"))
            .respond_with(
                wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({"id": "m1"})),
            )
            .mount(&server)
            .await;

        let temp_dir = tempfile::tempdir().unwrap();
        let path = temp_dir.path().join("message.eml");
        let err = run_read(
            &client,
            "m1",
            ReadDetail::Raw,
            Some(path.to_str().unwrap()),
            &ReadOutputFormat::Table,
            false,
        )
        .await
        .unwrap_err();
        assert!(err.to_string().contains("no `raw` field"));
        assert!(!path.exists());
    }

    // ── ReadOutputFormat::Markdown ──────────────────────────────────

    #[tokio::test]
    async fn run_read_markdown_writes_rendered_markdown_to_out_file() {
        let server = wiremock::MockServer::start().await;
        let client = client_with_bootstrapped_token(&server).await;
        let source = "Subject: Hi\r\nFrom: a@example.com\r\n\r\nBody text.";
        let encoded = base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(source);
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path("/gmail/v1/users/me/messages/m1"))
            .and(wiremock::matchers::query_param("format", "raw"))
            .respond_with(
                wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({
                    "id": "m1",
                    "raw": encoded,
                })),
            )
            .mount(&server)
            .await;

        let temp_dir = tempfile::tempdir().unwrap();
        let path = temp_dir.path().join("message.md");
        run_read(
            &client,
            "m1",
            ReadDetail::Full,
            Some(path.to_str().unwrap()),
            &ReadOutputFormat::Markdown,
            false,
        )
        .await
        .unwrap();

        let content = fs::read_to_string(&path).unwrap();
        assert!(content.contains("# Hi"));
        assert!(content.contains("Body text."));
    }

    #[tokio::test]
    async fn run_read_markdown_ignores_detail_and_always_fetches_raw() {
        let server = wiremock::MockServer::start().await;
        let client = client_with_bootstrapped_token(&server).await;
        let source = "Subject: Hi\r\n\r\nBody.";
        let encoded = base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(source);
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path("/gmail/v1/users/me/messages/m1"))
            .and(wiremock::matchers::query_param("format", "raw"))
            .respond_with(
                wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({
                    "id": "m1",
                    "raw": encoded,
                })),
            )
            .expect(1)
            .mount(&server)
            .await;

        // `--detail minimal` would normally request `format=minimal`; the
        // mock above only matches `format=raw`, so a request for anything
        // else 404s against wiremock's unmatched-request default and this
        // would fail if `-o markdown` didn't override `detail`.
        run_read(
            &client,
            "m1",
            ReadDetail::Minimal,
            None,
            &ReadOutputFormat::Markdown,
            false,
        )
        .await
        .unwrap();
    }

    #[tokio::test]
    async fn run_read_markdown_prints_to_stdout_without_out_file() {
        let server = wiremock::MockServer::start().await;
        let client = client_with_bootstrapped_token(&server).await;
        let source = "Subject: Hi\r\n\r\nBody.";
        let encoded = base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(source);
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path("/gmail/v1/users/me/messages/m1"))
            .and(wiremock::matchers::query_param("format", "raw"))
            .respond_with(
                wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({
                    "id": "m1",
                    "raw": encoded,
                })),
            )
            .mount(&server)
            .await;

        run_read(
            &client,
            "m1",
            ReadDetail::Full,
            None,
            &ReadOutputFormat::Markdown,
            false,
        )
        .await
        .unwrap();
    }

    #[tokio::test]
    async fn run_read_markdown_propagates_decode_errors() {
        let server = wiremock::MockServer::start().await;
        let client = client_with_bootstrapped_token(&server).await;
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path("/gmail/v1/users/me/messages/m1"))
            .and(wiremock::matchers::query_param("format", "raw"))
            .respond_with(
                wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({"id": "m1"})),
            )
            .mount(&server)
            .await;

        let err = run_read(
            &client,
            "m1",
            ReadDetail::Full,
            None,
            &ReadOutputFormat::Markdown,
            false,
        )
        .await
        .unwrap_err();
        assert!(err.to_string().contains("no `raw` field"));
    }

    #[tokio::test]
    async fn run_read_table_path_writes_to_stdout() {
        let server = wiremock::MockServer::start().await;
        let client = client_with_bootstrapped_token(&server).await;
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path("/gmail/v1/users/me/messages/m1"))
            .respond_with(
                wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({"id": "m1"})),
            )
            .mount(&server)
            .await;

        run_read(
            &client,
            "m1",
            ReadDetail::Full,
            None,
            &ReadOutputFormat::Table,
            false,
        )
        .await
        .unwrap();
    }

    #[tokio::test]
    async fn run_read_json_path_returns_ok() {
        let server = wiremock::MockServer::start().await;
        let client = client_with_bootstrapped_token(&server).await;
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path("/gmail/v1/users/me/messages/m1"))
            .respond_with(
                wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({"id": "m1"})),
            )
            .mount(&server)
            .await;

        run_read(
            &client,
            "m1",
            ReadDetail::Full,
            None,
            &ReadOutputFormat::Json,
            false,
        )
        .await
        .unwrap();
    }

    #[tokio::test]
    async fn run_read_yaml_path_returns_ok() {
        let server = wiremock::MockServer::start().await;
        let client = client_with_bootstrapped_token(&server).await;
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path("/gmail/v1/users/me/messages/m1"))
            .respond_with(
                wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({"id": "m1"})),
            )
            .mount(&server)
            .await;

        run_read(
            &client,
            "m1",
            ReadDetail::Full,
            None,
            &ReadOutputFormat::Yaml,
            false,
        )
        .await
        .unwrap();
    }

    #[tokio::test]
    async fn run_read_yamls_path_returns_ok() {
        let server = wiremock::MockServer::start().await;
        let client = client_with_bootstrapped_token(&server).await;
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path("/gmail/v1/users/me/messages/m1"))
            .respond_with(
                wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({"id": "m1"})),
            )
            .mount(&server)
            .await;

        run_read(
            &client,
            "m1",
            ReadDetail::Full,
            None,
            &ReadOutputFormat::Yamls,
            false,
        )
        .await
        .unwrap();
    }

    #[tokio::test]
    async fn run_read_jsonl_path_returns_ok() {
        let server = wiremock::MockServer::start().await;
        let client = client_with_bootstrapped_token(&server).await;
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path("/gmail/v1/users/me/messages/m1"))
            .respond_with(
                wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({"id": "m1"})),
            )
            .mount(&server)
            .await;

        run_read(
            &client,
            "m1",
            ReadDetail::Full,
            None,
            &ReadOutputFormat::Jsonl,
            false,
        )
        .await
        .unwrap();
    }

    #[tokio::test]
    async fn run_read_propagates_api_errors() {
        let server = wiremock::MockServer::start().await;
        let client = client_with_bootstrapped_token(&server).await;
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path("/gmail/v1/users/me/messages/m1"))
            .respond_with(wiremock::ResponseTemplate::new(404).set_body_string("not found"))
            .mount(&server)
            .await;

        let err = run_read(
            &client,
            "m1",
            ReadDetail::Full,
            None,
            &ReadOutputFormat::Table,
            false,
        )
        .await
        .unwrap_err();
        assert!(err.to_string().contains("404"));
    }

    #[tokio::test]
    async fn run_read_uses_metadata_format_for_metadata_detail() {
        let server = wiremock::MockServer::start().await;
        let client = client_with_bootstrapped_token(&server).await;
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path("/gmail/v1/users/me/messages/m1"))
            .and(wiremock::matchers::query_param("format", "metadata"))
            .respond_with(
                wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({"id": "m1"})),
            )
            .expect(1)
            .mount(&server)
            .await;

        run_read(
            &client,
            "m1",
            ReadDetail::Metadata,
            None,
            &ReadOutputFormat::Table,
            false,
        )
        .await
        .unwrap();
    }

    #[tokio::test]
    async fn run_read_uses_minimal_format_for_minimal_detail() {
        let server = wiremock::MockServer::start().await;
        let client = client_with_bootstrapped_token(&server).await;
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path("/gmail/v1/users/me/messages/m1"))
            .and(wiremock::matchers::query_param("format", "minimal"))
            .respond_with(
                wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({"id": "m1"})),
            )
            .expect(1)
            .mount(&server)
            .await;

        run_read(
            &client,
            "m1",
            ReadDetail::Minimal,
            None,
            &ReadOutputFormat::Table,
            false,
        )
        .await
        .unwrap();
    }

    // ── ReadCommand::execute glue ────────────────────────────────────

    #[tokio::test]
    async fn execute_passes_message_id_through() {
        let server = wiremock::MockServer::start().await;
        let client = client_with_bootstrapped_token(&server).await;
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path("/gmail/v1/users/me/messages/m42"))
            .respond_with(
                wiremock::ResponseTemplate::new(200)
                    .set_body_json(serde_json::json!({"id": "m42"})),
            )
            .expect(1)
            .mount(&server)
            .await;

        let cmd = ReadCommand {
            message_id: "m42".to_string(),
            out_file: None,
            detail: ReadDetail::Full,
            output: ReadOutputFormat::Json,
            fold_quotes: false,
        };
        cmd.execute(&client).await.unwrap();
    }
}