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
//! Gmail CLI commands.

pub(crate) mod account;
pub(crate) mod auth;
pub(crate) mod extract_attachments;
pub(crate) mod format;
pub(crate) mod helpers;
pub(crate) mod label;
pub(crate) mod read;
pub(crate) mod render;
pub(crate) mod search;
pub(crate) mod sync;
pub(crate) mod sync_all;
pub(crate) mod thread;

use anyhow::Result;
use clap::{Parser, Subcommand};

use crate::gmail::account::GMAIL_ACCOUNT_ENV;
use crate::gmail::client::GmailClient;

/// Gmail: read Gmail messages, threads, and labels (and, with `gmail.modify`, mutate labels).
#[derive(Parser)]
pub struct GmailCommand {
    /// Selects a named Gmail account configured in
    /// `~/.omni-dev/settings.json` (AWS-CLI style, mirrors the top-level
    /// `--profile`) for this invocation.
    ///
    /// Orthogonal to `--profile`: switching the Gmail account never changes
    /// which profile is active, and vice versa (see
    /// [ADR-0066](../../../docs/adrs/adr-0066.md)). Overrides
    /// `OMNI_DEV_GMAIL_ACCOUNT`. Scoped to the `gmail` subtree — unlike
    /// `--profile`/`--instance` it is not usable before the `gmail`
    /// subcommand name, only after it (`gmail --account NAME <cmd>` or
    /// `gmail <cmd> --account NAME`), so it can't collide with an unrelated
    /// subcommand's own `--account` flag elsewhere in the CLI (e.g.
    /// `snowflake query --account`).
    #[arg(long, global = true, value_name = "NAME")]
    pub account: Option<String>,
    /// The Gmail subcommand to execute.
    #[command(subcommand)]
    pub command: GmailSubcommands,
}

/// Gmail subcommands.
#[derive(Subcommand)]
pub enum GmailSubcommands {
    /// Manages Gmail OAuth2 credentials (mirrors the `gmail_auth_status` MCP tool for `status`).
    Auth(auth::AuthCommand),
    /// Manages named Gmail accounts (mirrors the `gmail_account_list` MCP tool for `list`).
    Account(account::AccountCommand),
    /// Searches Gmail messages (mirrors the `gmail_search` MCP tool).
    Search(search::SearchCommand),
    /// Reads a single Gmail message (mirrors the `gmail_message_read` MCP tool).
    Read(read::ReadCommand),
    /// Reads a Gmail thread (mirrors the `gmail_thread_read` MCP tool).
    Thread(thread::ThreadCommand),
    /// Manages Gmail labels (mirrors the `gmail_label_list` MCP tool; `add`/`remove` are CLI-only in Phase 1).
    Label(label::LabelCommand),
    /// Maintains a durable local archive of a mailbox (CLI-only; no MCP equivalent).
    Sync(sync::SyncCommand),
    /// Maintains durable local archives for every account in
    /// `.omni-dev/gmail-sync.yaml`, concurrently (CLI-only; no MCP
    /// equivalent; ADR-0068).
    SyncAll(sync_all::SyncAllCommand),
    /// Retroactively extracts attachments for already-archived messages,
    /// without re-fetching from Gmail (CLI-only; no MCP equivalent; purely
    /// local, no client/credentials needed; #1510).
    ExtractAttachments(extract_attachments::ExtractAttachmentsCommand),
    /// Renders one or more archived `.eml` files as human-readable Markdown
    /// (CLI-only; no MCP equivalent; purely local, no client/credentials
    /// needed; #1513).
    Render(render::RenderCommand),
}

impl GmailCommand {
    /// Executes the Gmail command.
    ///
    /// `auth` manages credentials and must run without them; `account`
    /// manages which named account is selected and must equally run
    /// without a resolved client (`import-legacy`'s whole point is working
    /// in a pre-migration state). `sync-all` also runs without the shared
    /// client: it resolves one client per configured account itself
    /// (`helpers::create_client_for`, never the env var below, which is
    /// unsafe across its concurrent tasks — ADR-0068). `extract-attachments`
    /// also runs without a client — it never contacts Gmail at all, only
    /// the local archive under `--archive-dir`, so `--account` has no
    /// meaning for it either (#1510). Every other subcommand needs an
    /// authenticated client, which is resolved **once** here and threaded
    /// down so each leaf takes `&GmailClient` and stays free of process
    /// env. `render` also runs without a client — like
    /// `extract-attachments`, it only ever reads `.eml` files already on
    /// disk (#1513).
    pub async fn execute(self) -> Result<()> {
        let account = self.account;
        match self.command {
            GmailSubcommands::SyncAll(cmd) => {
                anyhow::ensure!(
                    account.is_none(),
                    "--account is not compatible with sync-all; configure accounts in \
                     .omni-dev/gmail-sync.yaml instead"
                );
                cmd.execute().await
            }
            GmailSubcommands::ExtractAttachments(cmd) => {
                anyhow::ensure!(
                    account.is_none(),
                    "--account is not compatible with extract-attachments; it operates on a \
                     local archive directory only"
                );
                cmd.execute()
            }
            GmailSubcommands::Render(cmd) => {
                anyhow::ensure!(
                    account.is_none(),
                    "--account is not compatible with render; it operates on local .eml files \
                     only"
                );
                cmd.execute()
            }
            command => {
                // Propagates --account to the env var for the duration of
                // this call only (`gmail::account::resolve_account` reads
                // it, issue #1500), mirroring `Cli::propagate_global_flags`'s
                // pattern: only set when present, so an existing ambient
                // OMNI_DEV_GMAIL_ACCOUNT still works when the flag is
                // omitted. The guard restores/removes it on drop at the end
                // of this scope, so execute() is safe to call more than once
                // per process (#1538).
                let _account_guard = account.as_ref().map(|account| {
                    crate::utils::env::ScopedEnvVar::set(GMAIL_ACCOUNT_ENV, account)
                });

                match command {
                    GmailSubcommands::Auth(cmd) => cmd.execute().await,
                    GmailSubcommands::Account(cmd) => cmd.execute(),
                    data => {
                        let client = helpers::create_client()?;
                        data.dispatch(&client).await
                    }
                }
            }
        }
    }
}

impl GmailSubcommands {
    /// Routes a non-`Auth`/`Account`/`SyncAll`/`ExtractAttachments`/`Render`
    /// subcommand against the shared client. Kept separate from credential
    /// resolution so it is testable without env (tests pass a client
    /// pointed at an unreachable URL). Those five arms are unreachable
    /// because all five are handled before client resolution in
    /// [`GmailCommand::execute`] — `SyncAll` builds its own per-account
    /// clients instead of using the shared one (ADR-0068), and
    /// `ExtractAttachments`/`Render` need no client at all (#1510, #1513).
    async fn dispatch(self, client: &GmailClient) -> Result<()> {
        match self {
            Self::Auth(_) => {
                unreachable!("Auth is dispatched before client resolution")
            }
            Self::Account(_) => {
                unreachable!("Account is dispatched before client resolution")
            }
            Self::SyncAll(_) => {
                unreachable!("SyncAll is dispatched before client resolution")
            }
            Self::ExtractAttachments(_) => {
                unreachable!("ExtractAttachments is dispatched before client resolution")
            }
            Self::Render(_) => {
                unreachable!("Render is dispatched before client resolution")
            }
            Self::Search(cmd) => cmd.execute(client).await,
            Self::Read(cmd) => cmd.execute(client).await,
            Self::Thread(cmd) => cmd.execute(client).await,
            Self::Label(cmd) => cmd.execute(client).await,
            Self::Sync(cmd) => cmd.execute(client).await,
        }
    }
}

#[cfg(test)]
#[allow(clippy::unwrap_used)]
mod tests {
    use super::*;
    use crate::cli::gmail::format::OutputFormat;
    use crate::gmail::auth::{GmailCredentials, GmailScope};
    use crate::gmail::client::GmailClient;
    use crate::utils::secret::Secret;

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

    /// A client pointed at an unreachable URL. Routing tests use it so a
    /// command runs through dispatch -> leaf -> the HTTP layer and fails
    /// with a connection error — exercising the routing without touching
    /// credentials, the process environment, or a mock server.
    fn dead_client() -> GmailClient {
        GmailClient::new("http://127.0.0.1:1", &dead_credentials()).unwrap()
    }

    // ── GmailCommand::execute glue ──────────────────────────────────
    //
    // The success path (`helpers::create_client()` succeeding, then
    // `data.dispatch(&client)` actually issuing a request) needs real
    // credentials and would hit the real Gmail API host — there's no
    // env-var override to redirect it at a mock server (see the
    // `mcp::gmail_tools` module doc). These tests cover the
    // credentials-missing error path, which is deterministic and
    // network-free.

    #[tokio::test]
    async fn execute_routes_auth_subcommand_and_surfaces_missing_credentials() {
        let guard = crate::gmail::test_support::EnvGuard::take();
        let _dir = guard.clear_credentials();

        let cmd = GmailCommand {
            account: None,
            command: GmailSubcommands::Auth(auth::AuthCommand {
                command: auth::AuthSubcommands::Status(auth::StatusCommand { all: false }),
            }),
        };
        let err = cmd.execute().await.unwrap_err();
        assert!(err.to_string().contains("not configured"));
    }

    #[tokio::test]
    async fn execute_non_auth_subcommand_errors_when_credentials_missing() {
        let guard = crate::gmail::test_support::EnvGuard::take();
        let _dir = guard.clear_credentials();

        let cmd = GmailCommand {
            account: None,
            command: GmailSubcommands::Search(search::SearchCommand {
                query: "label:finance".to_string(),
                limit: 10,
                enrich: false,
                concurrency: 4,
                output: OutputFormat::Table,
            }),
        };
        let err = cmd.execute().await.unwrap_err();
        assert!(err.to_string().contains("not configured"));
    }

    #[test]
    fn gmail_subcommands_auth_variant() {
        let cmd = GmailCommand {
            account: None,
            command: GmailSubcommands::Auth(auth::AuthCommand {
                command: auth::AuthSubcommands::Status(auth::StatusCommand { all: false }),
            }),
        };
        assert!(matches!(cmd.command, GmailSubcommands::Auth(_)));
    }

    #[test]
    fn gmail_subcommands_account_variant() {
        let cmd = GmailCommand {
            account: None,
            command: GmailSubcommands::Account(account::AccountCommand {
                command: account::AccountSubcommands::List(account::list::ListCommand {
                    output: OutputFormat::Table,
                }),
            }),
        };
        assert!(matches!(cmd.command, GmailSubcommands::Account(_)));
    }

    #[tokio::test]
    async fn execute_restores_account_env_var_after_return() {
        let guard = crate::gmail::test_support::EnvGuard::take();
        let _dir = guard.clear_credentials();

        let cmd = GmailCommand {
            account: Some("work".to_string()),
            command: GmailSubcommands::Account(account::AccountCommand {
                command: account::AccountSubcommands::List(account::list::ListCommand {
                    output: OutputFormat::Table,
                }),
            }),
        };
        cmd.execute().await.unwrap();
        assert_eq!(std::env::var(GMAIL_ACCOUNT_ENV).ok(), None);
    }

    #[tokio::test]
    async fn execute_restores_previous_account_env_var_after_return() {
        let guard = crate::gmail::test_support::EnvGuard::take();
        let _dir = guard.clear_credentials();
        std::env::set_var(GMAIL_ACCOUNT_ENV, "personal");

        let cmd = GmailCommand {
            account: Some("work".to_string()),
            command: GmailSubcommands::Account(account::AccountCommand {
                command: account::AccountSubcommands::List(account::list::ListCommand {
                    output: OutputFormat::Table,
                }),
            }),
        };
        cmd.execute().await.unwrap();
        assert_eq!(
            std::env::var(GMAIL_ACCOUNT_ENV).ok().as_deref(),
            Some("personal")
        );
    }

    #[tokio::test]
    async fn execute_does_not_leak_account_across_sequential_calls() {
        let guard = crate::gmail::test_support::EnvGuard::take();
        let _dir = guard.clear_credentials();

        let account_list_cmd = || GmailCommand {
            account: None,
            command: GmailSubcommands::Account(account::AccountCommand {
                command: account::AccountSubcommands::List(account::list::ListCommand {
                    output: OutputFormat::Table,
                }),
            }),
        };

        let first = GmailCommand {
            account: Some("alpha".to_string()),
            ..account_list_cmd()
        };
        first.execute().await.unwrap();
        assert_eq!(std::env::var(GMAIL_ACCOUNT_ENV).ok(), None);

        // If the first call's value had leaked, this second call — which
        // omits --account entirely — would still see it via the env var.
        account_list_cmd().execute().await.unwrap();
        assert_eq!(std::env::var(GMAIL_ACCOUNT_ENV).ok(), None);
    }

    #[tokio::test]
    async fn execute_absent_account_leaves_ambient_env_var_untouched() {
        let guard = crate::gmail::test_support::EnvGuard::take();
        let _dir = guard.clear_credentials();
        std::env::set_var(GMAIL_ACCOUNT_ENV, "personal");

        let cmd = GmailCommand {
            account: None,
            command: GmailSubcommands::Account(account::AccountCommand {
                command: account::AccountSubcommands::List(account::list::ListCommand {
                    output: OutputFormat::Table,
                }),
            }),
        };
        cmd.execute().await.unwrap();
        assert_eq!(
            std::env::var(GMAIL_ACCOUNT_ENV).ok().as_deref(),
            Some("personal")
        );
    }

    #[tokio::test]
    async fn execute_routes_account_list_without_client_resolution() {
        let guard = crate::gmail::test_support::EnvGuard::take();
        let _dir = guard.clear_credentials();

        let cmd = GmailCommand {
            account: None,
            command: GmailSubcommands::Account(account::AccountCommand {
                command: account::AccountSubcommands::List(account::list::ListCommand {
                    output: OutputFormat::Table,
                }),
            }),
        };
        // Succeeds even with zero credentials configured — proving Account
        // subcommands never resolve a client (unlike every other
        // subcommand, which errors on missing credentials).
        cmd.execute().await.unwrap();
    }

    #[tokio::test]
    async fn dispatch_routes_search() {
        let cmd = GmailSubcommands::Search(search::SearchCommand {
            query: "label:finance".to_string(),
            limit: 10,
            enrich: false,
            concurrency: 4,
            output: OutputFormat::Table,
        });
        assert!(cmd.dispatch(&dead_client()).await.is_err());
    }

    #[tokio::test]
    async fn dispatch_routes_read() {
        let cmd = GmailSubcommands::Read(read::ReadCommand {
            message_id: "msg1".to_string(),
            out_file: None,
            detail: read::ReadDetail::Full,
            output: read::ReadOutputFormat::Table,
            fold_quotes: false,
        });
        assert!(cmd.dispatch(&dead_client()).await.is_err());
    }

    #[tokio::test]
    async fn dispatch_routes_thread() {
        let cmd = GmailSubcommands::Thread(thread::ThreadCommand {
            thread_id: "t1".to_string(),
            output: OutputFormat::Table,
        });
        assert!(cmd.dispatch(&dead_client()).await.is_err());
    }

    #[tokio::test]
    async fn dispatch_routes_label_list() {
        let cmd = GmailSubcommands::Label(label::LabelCommand {
            command: label::LabelSubcommands::List(label::list::ListCommand {
                output: OutputFormat::Table,
            }),
        });
        assert!(cmd.dispatch(&dead_client()).await.is_err());
    }

    #[tokio::test]
    async fn dispatch_routes_label_add() {
        let cmd = GmailSubcommands::Label(label::LabelCommand {
            command: label::LabelSubcommands::Add(label::add::AddCommand {
                message_ids: vec!["m1".to_string()],
                label: "IMPORTANT".to_string(),
            }),
        });
        assert!(cmd.dispatch(&dead_client()).await.is_err());
    }

    #[tokio::test]
    async fn dispatch_routes_label_remove() {
        let cmd = GmailSubcommands::Label(label::LabelCommand {
            command: label::LabelSubcommands::Remove(label::remove::RemoveCommand {
                message_ids: vec!["m1".to_string()],
                label: "IMPORTANT".to_string(),
                force: true,
                dry_run: false,
            }),
        });
        assert!(cmd.dispatch(&dead_client()).await.is_err());
    }

    #[tokio::test]
    async fn dispatch_routes_sync() {
        let cmd = GmailSubcommands::Sync(sync::SyncCommand {
            output_dir: std::path::PathBuf::from("/tmp/does-not-matter"),
            query: None,
            full: false,
            concurrency: 4,
            dry_run: false,
            extract_attachments: false,
            quiet: false,
            output: OutputFormat::Table,
        });
        assert!(cmd.dispatch(&dead_client()).await.is_err());
    }

    fn sync_all_command() -> sync_all::SyncAllCommand {
        sync_all::SyncAllCommand {
            context_dir: None,
            concurrency: None,
            full: false,
            dry_run: false,
            quiet: false,
            output: OutputFormat::Table,
        }
    }

    #[tokio::test]
    async fn execute_rejects_account_flag_with_sync_all() {
        let guard = crate::gmail::test_support::EnvGuard::take();
        let _dir = guard.clear_credentials();

        let cmd = GmailCommand {
            account: Some("work".to_string()),
            command: GmailSubcommands::SyncAll(sync_all_command()),
        };
        let err = cmd.execute().await.unwrap_err();
        assert!(err
            .to_string()
            .contains("--account is not compatible with sync-all"));
    }

    #[tokio::test]
    async fn execute_sync_all_never_sets_the_account_env_var() {
        let guard = crate::gmail::test_support::EnvGuard::take();
        let dir = guard.clear_credentials();

        let cmd = GmailCommand {
            account: None,
            command: GmailSubcommands::SyncAll(sync_all::SyncAllCommand {
                context_dir: Some(dir.path().to_path_buf()),
                ..sync_all_command()
            }),
        };
        // No gmail-sync.yaml exists under `dir` — this is expected to
        // fail with a config-loading error, never a network/dispatch
        // error, proving `SyncAll` never reached the shared-client
        // `dispatch` path (which would panic on `unreachable!()`).
        let err = cmd.execute().await.unwrap_err();
        assert!(err.to_string().contains("no gmail-sync.yaml found"));
        assert_eq!(std::env::var(GMAIL_ACCOUNT_ENV).ok(), None);
    }

    #[tokio::test]
    async fn execute_routes_extract_attachments_without_client_resolution() {
        let guard = crate::gmail::test_support::EnvGuard::take();
        let _dir = guard.clear_credentials();
        let archive_dir = tempfile::tempdir().unwrap();

        let cmd = GmailCommand {
            account: None,
            command: GmailSubcommands::ExtractAttachments(
                extract_attachments::ExtractAttachmentsCommand {
                    archive_dir: archive_dir.path().to_path_buf(),
                    dry_run: false,
                    quiet: true,
                    output: OutputFormat::Table,
                },
            ),
        };
        // Succeeds even with zero credentials configured (an empty
        // archive is simply "nothing to do") — proving
        // `ExtractAttachments` never resolves a client, unlike every
        // subcommand routed through `dispatch`.
        cmd.execute().await.unwrap();
    }

    #[tokio::test]
    async fn execute_rejects_account_flag_with_extract_attachments() {
        let guard = crate::gmail::test_support::EnvGuard::take();
        let _dir = guard.clear_credentials();
        let archive_dir = tempfile::tempdir().unwrap();

        let cmd = GmailCommand {
            account: Some("work".to_string()),
            command: GmailSubcommands::ExtractAttachments(
                extract_attachments::ExtractAttachmentsCommand {
                    archive_dir: archive_dir.path().to_path_buf(),
                    dry_run: false,
                    quiet: true,
                    output: OutputFormat::Table,
                },
            ),
        };
        let err = cmd.execute().await.unwrap_err();
        assert!(err
            .to_string()
            .contains("--account is not compatible with extract-attachments"));
        assert_eq!(std::env::var(GMAIL_ACCOUNT_ENV).ok(), None);
    }

    #[tokio::test]
    async fn execute_routes_render_without_client_resolution() {
        let guard = crate::gmail::test_support::EnvGuard::take();
        let _dir = guard.clear_credentials();
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("m1.eml");
        std::fs::write(&path, "Subject: Hi\r\n\r\nBody.").unwrap();

        let cmd = GmailCommand {
            account: None,
            command: GmailSubcommands::Render(render::RenderCommand {
                paths: vec![path],
                archive_dir: None,
                all: false,
                out_dir: None,
                output: OutputFormat::Table,
                fold_quotes: false,
            }),
        };
        // Succeeds even with zero credentials configured — proving `Render`
        // never resolves a client, unlike every subcommand routed through
        // `dispatch`.
        cmd.execute().await.unwrap();
    }

    #[tokio::test]
    async fn execute_routes_render_archive_dir_without_client_resolution() {
        let guard = crate::gmail::test_support::EnvGuard::take();
        let _dir = guard.clear_credentials();
        let archive_dir = tempfile::tempdir().unwrap();

        let cmd = GmailCommand {
            account: None,
            command: GmailSubcommands::Render(render::RenderCommand {
                paths: Vec::new(),
                archive_dir: Some(archive_dir.path().to_path_buf()),
                all: true,
                out_dir: None,
                output: OutputFormat::Table,
                fold_quotes: false,
            }),
        };
        // Succeeds even with zero credentials configured (an empty archive
        // is simply "nothing to render") — proving `Render`'s
        // `--archive-dir --all` mode never resolves a client either.
        cmd.execute().await.unwrap();
    }

    #[tokio::test]
    async fn execute_rejects_account_flag_with_render() {
        let guard = crate::gmail::test_support::EnvGuard::take();
        let _dir = guard.clear_credentials();
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("m1.eml");
        std::fs::write(&path, "Subject: Hi\r\n\r\nBody.").unwrap();

        let cmd = GmailCommand {
            account: Some("work".to_string()),
            command: GmailSubcommands::Render(render::RenderCommand {
                paths: vec![path],
                archive_dir: None,
                all: false,
                out_dir: None,
                output: OutputFormat::Table,
                fold_quotes: false,
            }),
        };
        let err = cmd.execute().await.unwrap_err();
        assert!(err
            .to_string()
            .contains("--account is not compatible with render"));
        assert_eq!(std::env::var(GMAIL_ACCOUNT_ENV).ok(), None);
    }
}