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
//! Gmail History API wrapper.
//!
//! Same cursor-pagination shape as
//! [`crate::gmail::messages_api::MessagesApi`], but `startHistoryId` is a
//! required parameter rather than an optional filter. Recovered (and
//! adapted — see [`crate::gmail::types::HistoryMessageRef`]) from Phase 1's
//! `0db5a605` deletion; `gmail sync`'s incremental path
//! (`src/cli/gmail/sync/engine.rs`) is the intended, and first, caller.

use anyhow::Result;
use url::Url;

use crate::gmail::client::GmailClient;
use crate::gmail::types::HistoryListResponse;
use crate::utils::rate_limit::TokenBucket;

/// Maximum page size accepted by `GET /gmail/v1/users/{userId}/history`.
pub const MAX_PAGE_LIMIT: usize = 500;

/// Per-call upper bound on the number of history records returned by
/// [`HistoryApi::list_all`], even when the caller passes `limit = 0`.
pub const HARD_CAP: usize = 10_000;

/// Quota-unit cost of one `history.list` page request, per Google's
/// documented per-method quota cost table.
pub const HISTORY_LIST_COST_UNITS: u32 = 2;

/// History API façade.
#[derive(Debug)]
pub struct HistoryApi<'a> {
    client: &'a GmailClient,
}

impl<'a> HistoryApi<'a> {
    /// Wraps an existing [`GmailClient`] for history operations.
    #[must_use]
    pub fn new(client: &'a GmailClient) -> Self {
        Self { client }
    }

    /// Lists mailbox changes since `start_history_id`, returning a single
    /// page.
    ///
    /// Google returns 404 `notFound` when `start_history_id` is older than
    /// the mailbox's retention window (about a week); `gmail sync` catches
    /// that specific case and falls back to a full reconciliation pass.
    pub async fn list(
        &self,
        start_history_id: &str,
        history_types: &[&str],
        limit: usize,
        page_token: Option<&str>,
    ) -> Result<HistoryListResponse> {
        if limit > MAX_PAGE_LIMIT {
            return Err(anyhow::anyhow!(
                "`limit` must be <= {MAX_PAGE_LIMIT} (Gmail history.list per-page cap; use \
                 `list_all` to auto-paginate)"
            ));
        }
        let url = build_history_list_url(
            self.client.base_url(),
            start_history_id,
            history_types,
            limit,
            page_token,
        )?;
        self.client
            .get_parsed(url.as_str(), "Failed to parse history.list response")
            .await
    }

    /// Lists mailbox changes since `start_history_id`, auto-paginating via
    /// cursor as needed. `limit == 0` means "fetch every change up to
    /// [`HARD_CAP`]" — a deliberate safety limit for this general-purpose
    /// entry point. See [`Self::list_all_unbounded`] for the one caller that
    /// must not have it.
    pub async fn list_all(
        &self,
        start_history_id: &str,
        history_types: &[&str],
        limit: usize,
    ) -> Result<HistoryListResponse> {
        self.paginate(
            start_history_id,
            history_types,
            Some(effective_cap(limit)),
            None,
        )
        .await
    }

    /// Lists mailbox changes since `start_history_id`, auto-paginating with
    /// **no cap** — every page is fetched until Gmail stops returning a
    /// `nextPageToken`.
    ///
    /// `gmail sync`'s incremental path is the one caller for which a
    /// truncated listing is a correctness bug: a history burst larger than
    /// [`HARD_CAP`] (e.g. a large bulk label operation from another client)
    /// would otherwise silently drop `messagesAdded`/`messagesDeleted`/
    /// `labelsAdded`/`labelsRemoved` events past the cap (#1467), the same
    /// class of bug
    /// [`crate::gmail::messages_api::MessagesApi::search_all_unbounded_streaming`]
    /// fixes for the full-mailbox listing path.
    ///
    /// `limiter` paces each page request at [`HISTORY_LIST_COST_UNITS`]
    /// against the caller's quota budget, proactively rather than relying on
    /// reactive 429/403 retry.
    pub(crate) async fn list_all_unbounded(
        &self,
        start_history_id: &str,
        history_types: &[&str],
        limiter: &TokenBucket,
    ) -> Result<HistoryListResponse> {
        self.paginate(start_history_id, history_types, None, Some(limiter))
            .await
    }

    /// Shared pagination loop backing [`Self::list_all`] and
    /// [`Self::list_all_unbounded`]. `cap: None` means no ceiling at all —
    /// only an absent `nextPageToken` stops the loop.
    async fn paginate(
        &self,
        start_history_id: &str,
        history_types: &[&str],
        cap: Option<usize>,
        limiter: Option<&TokenBucket>,
    ) -> Result<HistoryListResponse> {
        let mut acc: Option<HistoryListResponse> = None;
        let mut page_token: Option<String> = None;
        loop {
            let collected = acc.as_ref().map_or(0, |r| r.history.len());
            let page_size = match cap {
                Some(cap) => (cap - collected).min(MAX_PAGE_LIMIT),
                None => MAX_PAGE_LIMIT,
            };
            if let Some(limiter) = limiter {
                limiter.acquire(HISTORY_LIST_COST_UNITS).await;
            }
            let page = self
                .list(
                    start_history_id,
                    history_types,
                    page_size,
                    page_token.as_deref(),
                )
                .await?;
            let next_token = page.next_page_token.clone();
            match acc.as_mut() {
                Some(existing) => {
                    existing.history.extend(page.history);
                    existing.next_page_token = page.next_page_token;
                    existing.history_id = page.history_id;
                }
                None => acc = Some(page),
            }
            let collected = acc.as_ref().map_or(0, |r| r.history.len());
            let cap_reached = cap.is_some_and(|cap| collected >= cap);
            if cap_reached || next_token.is_none() {
                break;
            }
            page_token = next_token;
        }
        let mut result = acc.unwrap_or_default();
        if let Some(cap) = cap {
            result.history.truncate(cap);
        }
        Ok(result)
    }
}

fn build_history_list_url(
    base_url: &str,
    start_history_id: &str,
    history_types: &[&str],
    limit: usize,
    page_token: Option<&str>,
) -> Result<Url> {
    let mut url = GmailClient::api_url(base_url, "/gmail/v1/users/me/history")?;
    {
        let mut pairs = url.query_pairs_mut();
        pairs.append_pair("startHistoryId", start_history_id);
        for history_type in history_types {
            pairs.append_pair("historyTypes", history_type);
        }
        if limit > 0 {
            pairs.append_pair("maxResults", &limit.to_string());
        }
        if let Some(token) = page_token {
            pairs.append_pair("pageToken", token);
        }
    }
    Ok(url)
}

/// Clamps a caller-supplied limit to [`HARD_CAP`], treating `0` as "fetch
/// as many as the cap allows".
fn effective_cap(limit: usize) -> usize {
    if limit == 0 {
        HARD_CAP
    } else {
        limit.min(HARD_CAP)
    }
}

#[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 std::sync::atomic::{AtomicUsize, Ordering};

    /// A `history.list` responder that serves `full_pages` full pages (each
    /// with a fresh `nextPageToken`) followed by one terminating page with no
    /// token — used to prove [`HistoryApi::list_all_unbounded`] keeps
    /// paginating past whatever [`HARD_CAP`] would have stopped
    /// [`HistoryApi::list_all`] at.
    struct SequentialPages {
        full_pages: usize,
        calls: AtomicUsize,
    }

    impl wiremock::Respond for SequentialPages {
        fn respond(&self, _req: &wiremock::Request) -> wiremock::ResponseTemplate {
            let call = self.calls.fetch_add(1, Ordering::SeqCst);
            if call < self.full_pages {
                let page: Vec<serde_json::Value> = (0..MAX_PAGE_LIMIT)
                    .map(|i| history_record_json(&format!("p{call}-h{i}")))
                    .collect();
                wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({
                    "history": page,
                    "nextPageToken": format!("token-{}", call + 1),
                }))
            } else {
                wiremock::ResponseTemplate::new(200)
                    .set_body_json(serde_json::json!({"history": Vec::<serde_json::Value>::new()}))
            }
        }
    }

    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,
        }
    }

    fn dead_client() -> GmailClient {
        // Routes the session's token endpoint to the same dead address —
        // otherwise `GmailSession` would try to refresh against the real
        // Google token endpoint before the API call is ever attempted.
        let mut client = GmailClient::new("http://127.0.0.1:1", &test_credentials()).unwrap();
        crate::gmail::client::test_support::replace_session(
            &mut client,
            &test_credentials(),
            "http://127.0.0.1:1",
        );
        client
    }

    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
    }

    fn history_record_json(id: &str) -> serde_json::Value {
        serde_json::json!({"id": id})
    }

    fn page_body(
        ids: &[&str],
        next_token: Option<&str>,
        final_history_id: Option<&str>,
    ) -> serde_json::Value {
        let history: Vec<serde_json::Value> =
            ids.iter().map(|id| history_record_json(id)).collect();
        let mut body = serde_json::json!({"history": history});
        if let Some(token) = next_token {
            body["nextPageToken"] = serde_json::json!(token);
        }
        if let Some(hid) = final_history_id {
            body["historyId"] = serde_json::json!(hid);
        }
        body
    }

    // ── URL builders (pure) ──────────────────────────────────────────

    #[test]
    fn build_history_list_url_always_includes_start_history_id() {
        let url =
            build_history_list_url("https://gmail.googleapis.com", "1000", &[], 0, None).unwrap();
        assert!(url
            .query_pairs()
            .any(|pair| pair == ("startHistoryId".into(), "1000".into())));
    }

    #[test]
    fn build_history_list_url_repeats_history_types() {
        let url = build_history_list_url(
            "https://gmail.googleapis.com",
            "1000",
            &["messageAdded", "labelAdded"],
            0,
            None,
        )
        .unwrap();
        let query: Vec<_> = url.query_pairs().collect();
        assert!(query.contains(&("historyTypes".into(), "messageAdded".into())));
        assert!(query.contains(&("historyTypes".into(), "labelAdded".into())));
    }

    #[test]
    fn build_history_list_url_rejects_invalid_base_url() {
        let err = build_history_list_url("not a url", "1000", &[], 0, None).unwrap_err();
        assert!(err.to_string().contains("Invalid Gmail base URL"));
    }

    // ── Standard error paths ─────────────────────────────────────────

    #[tokio::test]
    async fn list_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/history"))
            .respond_with(wiremock::ResponseTemplate::new(400).set_body_string("bad request"))
            .mount(&server)
            .await;

        let err = HistoryApi::new(&client)
            .list("1000", &[], 10, None)
            .await
            .unwrap_err();
        assert!(err.to_string().contains("400"));
    }

    #[tokio::test]
    async fn list_propagates_404_not_found_for_expired_start_history_id() {
        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/history"))
            .respond_with(
                wiremock::ResponseTemplate::new(404).set_body_json(serde_json::json!({
                    "error": {"message": "Not Found", "errors": [{"reason": "notFound"}]}
                })),
            )
            .mount(&server)
            .await;

        let err = HistoryApi::new(&client)
            .list("1", &[], 10, None)
            .await
            .unwrap_err();
        let msg = err.to_string();
        assert!(msg.contains("404"));
        assert!(msg.contains("notFound"));
    }

    #[tokio::test]
    async fn list_rejects_limit_above_max_page_limit_client_side() {
        let client = dead_client();
        let err = HistoryApi::new(&client)
            .list("1000", &[], MAX_PAGE_LIMIT + 1, None)
            .await
            .unwrap_err();
        let msg = err.to_string();
        assert!(msg.contains("limit"));
        assert!(msg.contains("list_all"));
    }

    #[tokio::test]
    async fn list_propagates_network_errors() {
        // `dead_client()` also points the session's token endpoint at the
        // dead address, so the failure surfaces during token acquisition
        // before the history.list request is ever attempted.
        let client = dead_client();
        let err = HistoryApi::new(&client)
            .list("1000", &[], 10, None)
            .await
            .unwrap_err();
        assert!(err
            .to_string()
            .contains("Failed to obtain a Gmail access token"));
    }

    #[tokio::test]
    async fn list_errors_on_malformed_response() {
        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/history"))
            .respond_with(wiremock::ResponseTemplate::new(200).set_body_string("not json"))
            .mount(&server)
            .await;

        let err = HistoryApi::new(&client)
            .list("1000", &[], 10, None)
            .await
            .unwrap_err();
        assert!(err.to_string().contains("Failed to parse"));
    }

    // ── Pagination ────────────────────────────────────────────────────

    #[tokio::test]
    async fn list_all_single_page_when_no_next_token() {
        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/history"))
            .respond_with(
                wiremock::ResponseTemplate::new(200).set_body_json(page_body(
                    &["a", "b"],
                    None,
                    Some("2000"),
                )),
            )
            .expect(1)
            .mount(&server)
            .await;

        let result = HistoryApi::new(&client)
            .list_all("1000", &[], 100)
            .await
            .unwrap();
        assert_eq!(result.history.len(), 2);
        assert_eq!(result.history_id.as_deref(), Some("2000"));
    }

    #[tokio::test]
    async fn list_all_follows_next_page_token_to_exhaustion() {
        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/history"))
            .and(wiremock::matchers::query_param_is_missing("pageToken"))
            .respond_with(
                wiremock::ResponseTemplate::new(200).set_body_json(page_body(
                    &["a", "b"],
                    Some("c1"),
                    None,
                )),
            )
            .expect(1)
            .mount(&server)
            .await;
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path("/gmail/v1/users/me/history"))
            .and(wiremock::matchers::query_param("pageToken", "c1"))
            .respond_with(
                wiremock::ResponseTemplate::new(200).set_body_json(page_body(
                    &["c"],
                    None,
                    Some("3000"),
                )),
            )
            .expect(1)
            .mount(&server)
            .await;

        let result = HistoryApi::new(&client)
            .list_all("1000", &[], 0)
            .await
            .unwrap();
        let ids: Vec<&str> = result.history.iter().map(|h| h.id.as_str()).collect();
        assert_eq!(ids, ["a", "b", "c"]);
        assert_eq!(result.history_id.as_deref(), Some("3000"));
    }

    #[tokio::test]
    async fn list_all_stops_at_explicit_limit() {
        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/history"))
            .respond_with(
                wiremock::ResponseTemplate::new(200).set_body_json(page_body(
                    &["a", "b", "c"],
                    Some("more"),
                    None,
                )),
            )
            .expect(1)
            .mount(&server)
            .await;

        let result = HistoryApi::new(&client)
            .list_all("1000", &[], 3)
            .await
            .unwrap();
        assert_eq!(result.history.len(), 3);
    }

    #[tokio::test]
    async fn list_all_truncates_to_hard_cap() {
        let server = wiremock::MockServer::start().await;
        let client = client_with_bootstrapped_token(&server).await;
        let full_page: Vec<serde_json::Value> = (0..MAX_PAGE_LIMIT)
            .map(|i| history_record_json(&format!("h{i}")))
            .collect();
        let body = serde_json::json!({"history": full_page, "nextPageToken": "always-more"});
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path("/gmail/v1/users/me/history"))
            .respond_with(wiremock::ResponseTemplate::new(200).set_body_json(body))
            .mount(&server)
            .await;

        let result = HistoryApi::new(&client)
            .list_all("1000", &[], 0)
            .await
            .unwrap();
        assert_eq!(result.history.len(), HARD_CAP);
    }

    #[tokio::test]
    async fn list_all_continues_past_empty_page_with_a_valid_next_page_token() {
        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/history"))
            .and(wiremock::matchers::query_param_is_missing("pageToken"))
            .respond_with(
                wiremock::ResponseTemplate::new(200).set_body_json(page_body(
                    &[],
                    Some("p2"),
                    None,
                )),
            )
            .expect(1)
            .mount(&server)
            .await;
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path("/gmail/v1/users/me/history"))
            .and(wiremock::matchers::query_param("pageToken", "p2"))
            .respond_with(
                wiremock::ResponseTemplate::new(200).set_body_json(page_body(
                    &["a"],
                    None,
                    Some("9"),
                )),
            )
            .expect(1)
            .mount(&server)
            .await;

        let result = HistoryApi::new(&client)
            .list_all("1000", &[], 0)
            .await
            .unwrap();
        assert_eq!(result.history.len(), 1);
    }

    #[tokio::test]
    async fn list_all_propagates_api_errors_on_first_page() {
        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/history"))
            .respond_with(wiremock::ResponseTemplate::new(403).set_body_string("nope"))
            .mount(&server)
            .await;

        let err = HistoryApi::new(&client)
            .list_all("1000", &[], 0)
            .await
            .unwrap_err();
        assert!(err.to_string().contains("403"));
    }

    // ── list_all_unbounded ───────────────────────────────────────────

    #[tokio::test]
    async fn list_all_unbounded_does_not_truncate_past_hard_cap() {
        let server = wiremock::MockServer::start().await;
        let client = client_with_bootstrapped_token(&server).await;
        // One more full page than `list_all` would allow before hitting
        // `HARD_CAP` — a regression back to the capped pagination path would
        // truncate this result to exactly `HARD_CAP`.
        let full_pages = HARD_CAP / MAX_PAGE_LIMIT + 1;
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path("/gmail/v1/users/me/history"))
            .respond_with(SequentialPages {
                full_pages,
                calls: AtomicUsize::new(0),
            })
            .mount(&server)
            .await;

        let limiter = TokenBucket::new(1_000_000, 1_000_000);
        let result = HistoryApi::new(&client)
            .list_all_unbounded("1000", &[], &limiter)
            .await
            .unwrap();

        assert_eq!(result.history.len(), full_pages * MAX_PAGE_LIMIT);
        assert!(result.history.len() > HARD_CAP);
    }

    #[tokio::test]
    async fn list_all_unbounded_draws_the_limiter_once_per_page() {
        let server = wiremock::MockServer::start().await;
        let client = client_with_bootstrapped_token(&server).await;
        let full_pages = 4;
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path("/gmail/v1/users/me/history"))
            .respond_with(SequentialPages {
                full_pages,
                calls: AtomicUsize::new(0),
            })
            .mount(&server)
            .await;

        // Zero refill: capacity alone is large enough that `acquire` never
        // actually waits, and with no refill between real HTTP round trips
        // the token count accurately reflects cumulative debits — a nonzero
        // refill rate this large would otherwise replenish the bucket back
        // to full between each network round trip, masking how many times
        // `acquire` was really called. This test only proves each of the 5
        // page requests (4 full + 1 terminating) draws
        // `HISTORY_LIST_COST_UNITS`; `TokenBucket` pacing itself is already
        // covered by `rate_limit.rs`'s own tests.
        let limiter = TokenBucket::new(1_000_000, 0);
        HistoryApi::new(&client)
            .list_all_unbounded("1000", &[], &limiter)
            .await
            .unwrap();

        let page_requests = 5;
        let expected_spent = f64::from(page_requests * HISTORY_LIST_COST_UNITS);
        // Exact integer-valued floats (units are whole numbers well within
        // f64's precision) — cast to compare, avoiding a lint against
        // strict floating-point equality that doesn't apply here.
        assert_eq!(
            limiter.available().await as i64,
            (1_000_000.0 - expected_spent) as i64
        );
    }

    // ── History record shapes (added/deleted/label changes) ──────────

    #[tokio::test]
    async fn list_parses_messages_added_with_label_ids() {
        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/history"))
            .respond_with(wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "history": [{
                    "id": "10",
                    "messagesAdded": [{
                        "message": {"id": "m1", "threadId": "t1", "labelIds": ["INBOX", "UNREAD"]}
                    }]
                }]
            })))
            .mount(&server)
            .await;

        let result = HistoryApi::new(&client)
            .list("1", &[], 10, None)
            .await
            .unwrap();
        let added = &result.history[0].messages_added[0].message;
        assert_eq!(added.id, "m1");
        assert_eq!(added.thread_id, "t1");
        assert_eq!(added.label_ids, vec!["INBOX", "UNREAD"]);
    }

    #[tokio::test]
    async fn list_parses_messages_deleted_and_label_changes() {
        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/history"))
            .respond_with(wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "history": [{
                    "id": "10",
                    "messagesDeleted": [{"message": {"id": "m2", "threadId": "t2"}}],
                    "labelsAdded": [{"message": {"id": "m3", "threadId": "t3"}, "labelIds": ["IMPORTANT"]}],
                    "labelsRemoved": [{"message": {"id": "m3", "threadId": "t3"}, "labelIds": ["UNREAD"]}]
                }]
            })))
            .mount(&server)
            .await;

        let result = HistoryApi::new(&client)
            .list("1", &[], 10, None)
            .await
            .unwrap();
        let record = &result.history[0];
        assert_eq!(record.messages_deleted[0].message.id, "m2");
        assert_eq!(record.labels_added[0].label_ids, vec!["IMPORTANT"]);
        assert_eq!(record.labels_removed[0].label_ids, vec!["UNREAD"]);
    }

    // ── effective_cap ─────────────────────────────────────────────────

    #[test]
    fn effective_cap_zero_is_hard_cap() {
        assert_eq!(effective_cap(0), HARD_CAP);
    }

    #[test]
    fn effective_cap_clamps_above_hard_cap() {
        assert_eq!(effective_cap(HARD_CAP + 5), HARD_CAP);
    }
}