bamboo-infrastructure 2026.5.4

Infrastructure services and integrations for the Bamboo agent framework
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
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
//! GitHub Copilot authentication handler.
//!
//! This module provides authentication handling for GitHub Copilot,
//! including device code flow, token caching, and automatic refresh.
//!
//! # Authentication Flow
//!
//! The authentication process follows GitHub's OAuth device flow:
//!
//! 1. **Device Code Request**: The client requests a device code from GitHub
//! 2. **User Authorization**: The user visits the verification URL and enters the code
//! 3. **Token Polling**: The client polls GitHub for an access token
//! 4. **Copilot Token Exchange**: The access token is exchanged for a Copilot API token
//! 5. **Token Caching**: Tokens are cached locally for future use
//!
//! # Example Usage
//!
//! ```rust,ignore
//! use std::sync::Arc;
//! use reqwest_middleware::ClientWithMiddleware;
//! use bamboo_agent::agent::llm::providers::copilot::auth::handler::CopilotAuthHandler;
//!
//! async fn authenticate() -> anyhow::Result<String> {
//!     // Create HTTP client with middleware
//!     let client = Arc::new(ClientWithMiddleware::new(/* ... */));
//!
//!     // Create auth handler with data directory
//!     let handler = CopilotAuthHandler::new(
//!         client,
//!         std::path::PathBuf::from("/path/to/bamboo-data-dir"),
//!         false, // Set to true for CLI mode
//!     );
//!
//!     // Get token (will trigger device flow if needed)
//!     let token = handler.get_token().await?;
//!     Ok(token)
//! }
//! ```
//!
//! # Token Caching Strategy
//!
//! The handler implements a multi-level token caching strategy:
//!
//! 1. **Copilot Token Cache**: Checks `.copilot_token.json` for valid tokens
//! 2. **Environment Variable**: Falls back to `COPILOT_API_KEY` if set
//! 3. **Access Token Cache**: Uses cached GitHub access token to request new Copilot token
//! 4. **Interactive Flow**: Only triggers device flow if all silent methods fail
//!
//! # Token Validation
//!
//! Tokens are validated with a 60-second buffer to ensure they don't expire
//! during use. This proactive refresh ensures seamless operation.

use crate::ProxyAuthRequiredError;
use anyhow::anyhow;
use lazy_static::lazy_static;
use reqwest::StatusCode;
use reqwest_middleware::ClientWithMiddleware;
use serde::{Deserialize, Serialize};
use std::{
    fs::{read_to_string, File},
    io::Write,
    path::PathBuf,
    sync::Arc,
    time::{Duration, SystemTime, UNIX_EPOCH},
};
use tokio::sync::Mutex;
use tokio::time::sleep;
use tracing::error;

use super::device_code::DeviceCodeResponse;

/// Copilot API configuration returned from GitHub.
///
/// Contains the authentication token, feature flags, and endpoint URLs
/// for the Copilot service.
///
/// This configuration is obtained by exchanging a GitHub access token
/// for a Copilot-specific token via the `/copilot_internal/v2/token` endpoint.
///
/// # Fields
///
/// - `token`: The Copilot API token used for authentication
/// - `expires_at`: Unix timestamp when the token expires
/// - `refresh_in`: Suggested refresh interval in seconds
/// - `endpoints`: API endpoints for Copilot services
/// - Various feature flags controlling available functionality
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct CopilotConfig {
    /// The Copilot API authentication token
    pub token: String,
    /// Whether code annotations are enabled for this account
    pub annotations_enabled: bool,
    /// Whether Copilot Chat is enabled for this account
    pub chat_enabled: bool,
    /// Whether Copilot Chat is enabled for JetBrains IDEs
    pub chat_jetbrains_enabled: bool,
    /// Whether code quote feature is enabled
    pub code_quote_enabled: bool,
    /// Whether code review feature is enabled
    pub code_review_enabled: bool,
    /// Whether code search is enabled
    pub codesearch: bool,
    /// Whether .copilotignore file support is enabled
    pub copilotignore_enabled: bool,
    /// API endpoints for various Copilot services
    pub endpoints: Endpoints,
    /// Unix timestamp when this token expires
    pub expires_at: u64,
    /// Whether this is an individual (vs enterprise) account
    pub individual: bool,
    /// User quota limit identifier, if applicable
    pub limited_user_quotas: Option<String>,
    /// Date when user quota resets, if applicable
    pub limited_user_reset_date: Option<String>,
    /// Whether 8k context prompts are enabled
    pub prompt_8k: bool,
    /// Public suggestions mode ("enabled", "disabled", etc.)
    pub public_suggestions: String,
    /// Recommended interval in seconds before refreshing token
    pub refresh_in: u64,
    /// Service SKU identifier
    pub sku: String,
    /// Internal load testing flag
    pub snippy_load_test_enabled: bool,
    /// Telemetry mode ("enabled", "disabled", etc.)
    pub telemetry: String,
    /// Unique tracking identifier for analytics
    pub tracking_id: String,
    /// Whether VS Code Electron fetcher v2 is enabled
    pub vsc_electron_fetcher_v2: bool,
    /// Whether Xcode support is enabled
    pub xcode: bool,
    /// Whether Xcode Chat is enabled
    pub xcode_chat: bool,
}

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

    /// Creates a test HTTP client without proxy for unit tests.
    fn test_http_client() -> Arc<ClientWithMiddleware> {
        use reqwest::Client as ReqwestClient;
        use reqwest_middleware::ClientBuilder;
        let client = ReqwestClient::builder().no_proxy().build().expect("client");
        Arc::new(ClientBuilder::new(client).build())
    }

    /// Creates a sample CopilotConfig for testing with specified expiration time.
    fn sample_config(expires_at: u64) -> CopilotConfig {
        CopilotConfig {
            token: "cached-token".to_string(),
            annotations_enabled: false,
            chat_enabled: true,
            chat_jetbrains_enabled: false,
            code_quote_enabled: false,
            code_review_enabled: false,
            codesearch: false,
            copilotignore_enabled: false,
            endpoints: Endpoints {
                api: Some("https://api.example.com".to_string()),
                origin_tracker: None,
                proxy: None,
                telemetry: None,
            },
            expires_at,
            individual: true,
            limited_user_quotas: None,
            limited_user_reset_date: None,
            prompt_8k: false,
            public_suggestions: "disabled".to_string(),
            refresh_in: 300,
            sku: "test".to_string(),
            snippy_load_test_enabled: false,
            telemetry: "disabled".to_string(),
            tracking_id: "test".to_string(),
            vsc_electron_fetcher_v2: false,
            xcode: false,
            xcode_chat: false,
        }
    }

    /// Tests that read_access_token properly trims whitespace and newlines.
    #[test]
    fn read_access_token_trims() {
        let dir = tempdir().expect("tempdir");
        let token_path = dir.path().join(".token");
        std::fs::write(&token_path, "  token-value \n").expect("write token");

        let token = CopilotAuthHandler::read_access_token(&token_path);
        assert_eq!(token.as_deref(), Some("token-value"));
    }

    /// Tests that CopilotConfig can be written to and read from cache.
    #[test]
    fn cached_copilot_config_round_trip() {
        let dir = tempdir().expect("tempdir");
        let handler = CopilotAuthHandler::new(test_http_client(), dir.path().to_path_buf(), false);
        let token_path = dir.path().join(".copilot_token.json");
        let config = sample_config(1234567890);

        handler
            .write_cached_copilot_config(&token_path, &config)
            .expect("write cache");
        let loaded = handler
            .read_cached_copilot_config(&token_path)
            .expect("read cache");

        assert_eq!(loaded.token, config.token);
        assert_eq!(loaded.expires_at, config.expires_at);
    }

    /// Tests that token validation uses a 60-second buffer.
    ///
    /// Tokens expiring within 60 seconds should be considered invalid
    /// to ensure proactive refresh.
    #[test]
    fn copilot_token_expiry_buffer() {
        let dir = tempdir().expect("tempdir");
        let handler = CopilotAuthHandler::new(test_http_client(), dir.path().to_path_buf(), false);
        let now = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .map(|duration| duration.as_secs())
            .unwrap_or(0);

        let valid = sample_config(now + 120);
        let stale = sample_config(now + 30);

        assert!(handler.is_copilot_token_valid(&valid));
        assert!(!handler.is_copilot_token_valid(&stale));
    }

    #[test]
    fn access_token_should_only_be_discarded_on_auth_errors() {
        let err_401 =
            anyhow::Error::msg("Copilot token request failed: HTTP 401 - bad credentials");
        assert!(CopilotAuthHandler::should_discard_access_token(&err_401));

        let err_403 = anyhow::Error::msg("Copilot token request failed: HTTP 403 - forbidden");
        assert!(CopilotAuthHandler::should_discard_access_token(&err_403));

        let err_407 = anyhow::Error::new(ProxyAuthRequiredError);
        assert!(!CopilotAuthHandler::should_discard_access_token(&err_407));

        let err_503 =
            anyhow::Error::msg("Copilot token request failed: HTTP 503 - service unavailable");
        assert!(!CopilotAuthHandler::should_discard_access_token(&err_503));
    }
}

/// API endpoint configuration for Copilot services.
///
/// Contains URLs for various Copilot API endpoints returned during
/// the token exchange process.
///
/// # Fields
///
/// - `api`: Primary API endpoint for Copilot requests
/// - `origin_tracker`: Endpoint for tracking request origins
/// - `proxy`: Proxy endpoint for proxied requests
/// - `telemetry`: Endpoint for sending telemetry data
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct Endpoints {
    /// Primary Copilot API endpoint (e.g., "https://api.githubcopilot.com")
    pub api: Option<String>,
    /// Origin tracking service endpoint
    pub origin_tracker: Option<String>,
    /// Proxy service endpoint for proxied API calls
    pub proxy: Option<String>,
    /// Telemetry collection endpoint
    pub telemetry: Option<String>,
}

/// Access token response from GitHub OAuth.
///
/// Contains the access token or error information from the OAuth device flow.
/// This is the response from GitHub's `/login/oauth/access_token` endpoint
/// when polling for authorization completion.
///
/// # Fields
///
/// - `access_token`: The OAuth access token on successful authorization
/// - `token_type`: Token type (typically "bearer")
/// - `scope`: OAuth scopes granted to the token
/// - `error`: Error code if authorization failed or is pending
/// - `error_description`: Human-readable error description
#[derive(Debug, Deserialize)]
pub(crate) struct AccessTokenResponse {
    /// The OAuth access token (present on successful authorization)
    pub access_token: Option<String>,
    /// Token type (typically "bearer")
    #[allow(dead_code)] // Needed for JSON deserialization from GitHub API
    pub token_type: Option<String>,
    /// OAuth scopes granted to this token
    #[allow(dead_code)] // Needed for JSON deserialization from GitHub API
    pub scope: Option<String>,
    /// Error code (e.g., "authorization_pending", "slow_down", "expired_token")
    pub error: Option<String>,
    /// Human-readable error description
    #[serde(rename = "error_description")]
    pub error_description: Option<String>,
}

impl AccessTokenResponse {
    /// Creates a new access token response from a token string.
    ///
    /// This is a convenience constructor for creating an `AccessTokenResponse`
    /// from a previously cached token string.
    ///
    /// # Arguments
    ///
    /// * `token` - The access token string
    ///
    /// # Example
    ///
    /// ```ignore
    /// use bamboo_agent::agent::llm::providers::copilot::auth::handler::AccessTokenResponse;
    ///
    /// let response = AccessTokenResponse::from_token("gho_xxxx".to_string());
    /// assert_eq!(response.access_token, Some("gho_xxxx".to_string()));
    /// ```
    pub(crate) fn from_token(token: String) -> Self {
        Self {
            access_token: Some(token),
            token_type: None,
            scope: None,
            error: None,
            error_description: None,
        }
    }
}

// Global lock for chat token operations.
//
// This mutex ensures that only one token request can be in flight at a time
// across the entire application. This prevents race conditions where multiple
// concurrent requests could trigger separate authentication flows.
//
// The lock is acquired in `CopilotAuthHandler::get_chat_token` before
// attempting silent authentication or starting a new device flow.
lazy_static! {
    static ref CHAT_TOKEN_LOCK: Mutex<()> = Mutex::new(());
}

/// Handler for GitHub Copilot authentication.
///
/// Manages the complete authentication lifecycle including:
/// - Device code flow for initial authentication
/// - Token caching and validation
/// - Automatic token refresh
/// - Silent authentication attempts
///
/// # Architecture
///
/// The handler implements a hierarchical token resolution strategy:
///
/// 1. **Cached Copilot Token**: Check local cache for valid token
/// 2. **Environment Variable**: Check `COPILOT_API_KEY`
/// 3. **Cached Access Token**: Use cached GitHub token to fetch new Copilot token
/// 4. **Interactive Flow**: Prompt user via device code flow
///
/// # Thread Safety
///
/// The handler is thread-safe and can be cloned cheaply. Authentication
/// operations are protected by a global lock to prevent concurrent flows.
///
/// # Example
///
/// ```rust,ignore
/// use std::sync::Arc;
/// use reqwest_middleware::ClientWithMiddleware;
/// use bamboo_agent::agent::llm::providers::copilot::auth::handler::CopilotAuthHandler;
///
/// async fn example() -> anyhow::Result<()> {
///     let client = Arc::new(ClientWithMiddleware::new(/* ... */));
///     let handler = CopilotAuthHandler::new(
///         client,
///         std::path::PathBuf::from("/path/to/bamboo-data-dir"),
///         false,
///     );
///
///     // Will use cached token or trigger device flow
///     let token = handler.get_token().await?;
///     println!("Got token: {}", token);
///     Ok(())
/// }
/// ```
#[derive(Debug, Clone)]
pub struct CopilotAuthHandler {
    /// HTTP client with middleware for retry logic
    client: Arc<ClientWithMiddleware>,
    /// Directory for storing cached tokens
    app_data_dir: PathBuf,
    /// Whether to print authentication instructions to console
    headless_auth: bool,
    /// GitHub API base URL (customizable for testing)
    github_api_base_url: String,
    /// GitHub login base URL (customizable for testing)
    github_login_base_url: String,
}

impl CopilotAuthHandler {
    /// Creates a new authentication handler.
    ///
    /// # Arguments
    ///
    /// * `client` - HTTP client with middleware for retry logic and error handling
    /// * `app_data_dir` - Directory for storing cached tokens (`.token` and `.copilot_token.json`)
    /// * `headless_auth` - Whether to print authentication instructions to console.
    ///   Set to `true` for CLI applications, `false` for GUI applications.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// use std::sync::Arc;
    /// use reqwest_middleware::ClientWithMiddleware;
    /// use bamboo_agent::agent::llm::providers::copilot::auth::handler::CopilotAuthHandler;
    ///
    /// let client = Arc::new(ClientWithMiddleware::new(/* ... */));
    /// let handler = CopilotAuthHandler::new(
    ///     client,
    ///     std::path::PathBuf::from("/path/to/bamboo-data-dir"),
    ///     true, // CLI mode
    /// );
    /// ```
    pub fn new(
        client: Arc<ClientWithMiddleware>,
        app_data_dir: PathBuf,
        headless_auth: bool,
    ) -> Self {
        CopilotAuthHandler {
            client,
            app_data_dir,
            headless_auth,
            github_api_base_url: "https://api.github.com".to_string(),
            github_login_base_url: "https://github.com".to_string(),
        }
    }

    /// Returns the application data directory path.
    ///
    /// This directory contains cached tokens:
    /// - `.token`: GitHub OAuth access token
    /// - `.copilot_token.json`: Copilot API configuration
    pub fn app_data_dir(&self) -> &PathBuf {
        &self.app_data_dir
    }

    /// Sets a custom GitHub API base URL for testing.
    ///
    /// This allows tests to mock GitHub's API without hitting production.
    #[cfg(test)]
    fn with_github_api_base_url(mut self, url: impl Into<String>) -> Self {
        self.github_api_base_url = url.into();
        self
    }

    /// Sets a custom GitHub login base URL for testing.
    ///
    /// This allows tests to mock GitHub's OAuth endpoints without hitting production.
    #[cfg(test)]
    fn with_github_login_base_url(mut self, url: impl Into<String>) -> Self {
        self.github_login_base_url = url.into();
        self
    }

    /// Performs authentication and returns an access token.
    ///
    /// This is the primary entry point for authentication. It will attempt
    /// silent authentication first, then fall back to interactive device flow
    /// if necessary.
    ///
    /// # Returns
    ///
    /// A Copilot API token on success.
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - All authentication methods fail
    /// - User denies authorization during device flow
    /// - Device code expires before authorization
    /// - Network errors occur
    pub async fn authenticate(&self) -> anyhow::Result<String> {
        self.get_chat_token().await
    }

    /// Ensures the handler is authenticated, without returning the token.
    ///
    /// This is useful for pre-authenticating or verifying credentials
    /// without needing the actual token value.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// # use bamboo_agent::agent::llm::providers::copilot::auth::handler::CopilotAuthHandler;
    /// # async fn example(handler: CopilotAuthHandler) -> anyhow::Result<()> {
    /// // Pre-authenticate before starting the application
    /// handler.ensure_authenticated().await?;
    /// println!("Authentication successful!");
    /// # Ok(())
    /// # }
    /// ```
    pub async fn ensure_authenticated(&self) -> anyhow::Result<()> {
        self.get_chat_token().await.map(|_| ())
    }

    /// Gets the current access token, authenticating if necessary.
    ///
    /// Alias for [`authenticate`](Self::authenticate).
    pub async fn get_token(&self) -> anyhow::Result<String> {
        self.get_chat_token().await
    }

    /// Gets a chat token, using cached credentials or triggering device flow.
    ///
    /// This method attempts silent authentication first, then falls back
    /// to interactive device code flow if necessary.
    ///
    /// # Silent Authentication Priority
    ///
    /// 1. Check cached Copilot token (`.copilot_token.json`)
    /// 2. Check `COPILOT_API_KEY` environment variable
    /// 3. Check cached GitHub access token (`.token`) and exchange for new Copilot token
    ///
    /// # Thread Safety
    ///
    /// This method acquires a global lock to prevent concurrent authentication
    /// flows. Only one authentication attempt can be in progress at a time.
    ///
    /// # Returns
    ///
    /// A valid Copilot API token.
    ///
    /// # Errors
    ///
    /// Returns an error if all authentication methods fail.
    pub async fn get_chat_token(&self) -> anyhow::Result<String> {
        // Acquire global lock to ensure sequential execution
        let _guard = CHAT_TOKEN_LOCK.lock().await;

        // Try silent authentication first
        if let Some(token) = self.try_get_chat_token_silent().await? {
            return Ok(token);
        }

        // Need interactive authentication
        let device_code = self.start_authentication().await?;
        let copilot_config = self.complete_authentication(&device_code).await?;
        Ok(copilot_config.token)
    }

    /// Reads an access token from a file, trimming whitespace.
    ///
    /// This utility function reads a token from a file and trims any
    /// leading/trailing whitespace or newlines.
    ///
    /// # Arguments
    ///
    /// * `token_path` - Path to the token file
    ///
    /// # Returns
    ///
    /// - `Some(token)` if the file exists and contains non-whitespace content
    /// - `None` if the file doesn't exist or is empty/whitespace only
    fn read_access_token(token_path: &PathBuf) -> Option<String> {
        if !token_path.exists() {
            return None;
        }
        let access_token_str = read_to_string(token_path).ok()?;
        let trimmed = access_token_str.trim();
        if trimmed.is_empty() {
            None
        } else {
            Some(trimmed.to_string())
        }
    }

    /// Reads a cached Copilot configuration from a file.
    ///
    /// Attempts to deserialize a JSON-formatted Copilot configuration
    /// from the specified file.
    ///
    /// # Arguments
    ///
    /// * `token_path` - Path to the JSON cache file
    ///
    /// # Returns
    ///
    /// - `Some(config)` if the file exists and contains valid JSON
    /// - `None` if the file doesn't exist or has invalid JSON
    fn read_cached_copilot_config(&self, token_path: &PathBuf) -> Option<CopilotConfig> {
        let cached_str = read_to_string(token_path).ok()?;
        serde_json::from_str::<CopilotConfig>(&cached_str).ok()
    }

    /// Writes a Copilot configuration to a cache file.
    ///
    /// Serializes the configuration as JSON and writes it to the specified file.
    ///
    /// # Arguments
    ///
    /// * `token_path` - Path where the JSON should be written
    /// * `copilot_config` - Configuration to cache
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - JSON serialization fails
    /// - File creation fails
    /// - Writing to file fails
    fn write_cached_copilot_config(
        &self,
        token_path: &PathBuf,
        copilot_config: &CopilotConfig,
    ) -> anyhow::Result<()> {
        let serialized = serde_json::to_string(copilot_config)?;
        let mut file = File::create(token_path)?;
        file.write_all(serialized.as_bytes())?;
        Ok(())
    }

    /// Checks if a Copilot token is valid with a 60-second buffer.
    ///
    /// This method checks whether the token has expired, with a 60-second
    /// buffer to ensure tokens are refreshed before they actually expire.
    ///
    /// # Arguments
    ///
    /// * `copilot_config` - Configuration containing the token expiration time
    ///
    /// # Returns
    ///
    /// - `true` if the token is valid for at least 60 more seconds
    /// - `false` if the token has expired or will expire within 60 seconds
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// # use bamboo_agent::agent::llm::providers::copilot::auth::handler::{CopilotAuthHandler, CopilotConfig};
    /// # fn example(handler: CopilotAuthHandler, config: CopilotConfig) {
    /// if handler.is_copilot_token_valid(&config) {
    ///     println!("Token is valid");
    /// } else {
    ///     println!("Token needs refresh");
    /// }
    /// # }
    /// ```
    fn is_copilot_token_valid(&self, copilot_config: &CopilotConfig) -> bool {
        let now = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .map(|duration| duration.as_secs())
            .unwrap_or(0);
        copilot_config.expires_at.saturating_sub(60) > now
    }

    /// Requests a device code from GitHub for OAuth flow.
    ///
    /// This is the first step in the OAuth device flow. It requests a
    /// device code and user code from GitHub that the user must enter
    /// at the verification URL.
    ///
    /// # Returns
    ///
    /// A [`DeviceCodeResponse`] containing:
    /// - `device_code`: Unique identifier for this authentication session
    /// - `user_code`: Code the user must enter at the verification URL
    /// - `verification_uri`: URL where user should enter the code
    /// - `expires_in`: Seconds until the device code expires
    /// - `interval`: Recommended polling interval in seconds
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - GitHub API is unreachable
    /// - Proxy authentication is required
    /// - API returns an error response
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// # use bamboo_agent::agent::llm::providers::copilot::auth::handler::CopilotAuthHandler;
    /// # async fn example(handler: CopilotAuthHandler) -> anyhow::Result<()> {
    /// let device_code = handler.get_device_code().await?;
    /// println!("Visit: {}", device_code.verification_uri);
    /// println!("Enter code: {}", device_code.user_code);
    /// # Ok(())
    /// # }
    /// ```
    pub(super) async fn get_device_code(&self) -> anyhow::Result<DeviceCodeResponse> {
        let params = [
            ("client_id", "Iv1.b507a08c87ecfe98"),
            ("scope", "read:user"),
        ];
        let url = format!("{}/login/device/code", self.github_login_base_url);

        let response = self
            .client
            .post(&url)
            .header("Accept", "application/json")
            .header("User-Agent", "BambooCopilot/1.0")
            .form(&params)
            .send()
            .await?;

        if response.status() == StatusCode::PROXY_AUTHENTICATION_REQUIRED {
            return Err(anyhow!(ProxyAuthRequiredError));
        }

        let status = response.status();
        if !status.is_success() {
            let text = response.text().await.unwrap_or_default();
            return Err(anyhow!(
                "Device code request failed: HTTP {} - {}",
                status,
                text
            ));
        }

        Ok(response.json::<DeviceCodeResponse>().await?)
    }

    /// Starts the authentication process by getting a device code.
    ///
    /// This method initiates the OAuth device flow by requesting a device
    /// code from GitHub. If `headless_auth` is `false`, it prints user-friendly
    /// instructions to the console.
    ///
    /// # Display Behavior
    ///
    /// - **Headless mode (`headless_auth = true`)**: Prints full instructions with ASCII art
    /// - **GUI mode (`headless_auth = false`)**: Returns device code for custom UI
    ///
    /// # Returns
    ///
    /// A [`DeviceCodeResponse`] with the device code and verification information.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// # use bamboo_agent::agent::llm::providers::copilot::auth::handler::CopilotAuthHandler;
    /// # async fn example(handler: CopilotAuthHandler) -> anyhow::Result<()> {
    /// let device_code = handler.start_authentication().await?;
    /// // In GUI mode, display these values to the user
    /// println!("URL: {}", device_code.verification_uri);
    /// println!("Code: {}", device_code.user_code);
    /// # Ok(())
    /// # }
    /// ```
    pub async fn start_authentication(&self) -> anyhow::Result<DeviceCodeResponse> {
        let device_code = self.get_device_code().await?;

        if self.headless_auth {
            // CLI mode: print to console
            println!("\n╔════════════════════════════════════════════════════════════╗");
            println!("║     🔐 GitHub Copilot Authorization Required              ║");
            println!("╚════════════════════════════════════════════════════════════╝");
            println!();
            println!("  1. Open your browser and navigate to:");
            println!("     {}", device_code.verification_uri);
            println!();
            println!("  2. Enter the following code:");
            println!();
            println!("     ┌─────────────────────────┐");
            println!("     │  {:^23} │", device_code.user_code);
            println!("     └─────────────────────────┘");
            println!();
            println!("  3. Click 'Authorize' and wait...");
            println!();
            println!(
                "  ⏳ Waiting for authorization (expires in {} seconds)...",
                device_code.expires_in
            );
            println!();
        }

        Ok(device_code)
    }

    /// Completes authentication by polling for access token and exchanging for Copilot token.
    ///
    /// This method completes the OAuth flow by:
    /// 1. Polling GitHub for the access token (waits for user authorization)
    /// 2. Exchanging the access token for a Copilot API token
    /// 3. Caching both tokens to disk for future use
    ///
    /// # Arguments
    ///
    /// * `device_code` - Device code response from [`start_authentication`](Self::start_authentication)
    ///
    /// # Returns
    ///
    /// A [`CopilotConfig`] containing the Copilot API token and configuration.
    ///
    /// # Side Effects
    ///
    /// Writes the following files to `app_data_dir`:
    /// - `.token`: GitHub OAuth access token
    /// - `.copilot_token.json`: Copilot API configuration
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - User denies authorization
    /// - Device code expires before authorization
    /// - Token exchange fails
    /// - File writing fails
    pub async fn complete_authentication(
        &self,
        device_code: &DeviceCodeResponse,
    ) -> anyhow::Result<CopilotConfig> {
        let access_token = self.get_access_token(device_code).await?;

        // Extract access token string before passing to get_copilot_token
        let access_token_str = access_token
            .access_token
            .clone()
            .ok_or_else(|| anyhow!("Access token not found"))?;

        let copilot_config = self.get_copilot_token(access_token).await?;

        // Write tokens to disk
        let token_path = self.app_data_dir.join(".token");
        let copilot_token_path = self.app_data_dir.join(".copilot_token.json");

        // Write access token
        let mut file = File::create(&token_path)?;
        file.write_all(access_token_str.as_bytes())?;

        // Write copilot config
        self.write_cached_copilot_config(&copilot_token_path, &copilot_config)?;

        Ok(copilot_config)
    }

    /// Attempts silent authentication without user interaction.
    ///
    /// This method tries multiple authentication strategies in order of preference,
    /// all of which can succeed without requiring user interaction:
    ///
    /// 1. **Cached Copilot Token**: Load from `.copilot_token.json` if still valid
    /// 2. **Environment Variable**: Check `COPILOT_API_KEY`
    /// 3. **Cached Access Token**: Use cached GitHub token to fetch new Copilot token
    ///
    /// # Returns
    ///
    /// - `Ok(Some(token))` if silent authentication succeeded
    /// - `Ok(None)` if silent authentication is not possible (triggers interactive flow)
    /// - `Err(...)` if an unexpected error occurred
    ///
    /// # Side Effects
    ///
    /// If using a cached access token, this method will:
    /// - Fetch a new Copilot token from GitHub
    /// - Cache the new Copilot token to `.copilot_token.json`
    /// - Remove the cached access token if it's invalid
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// # use bamboo_agent::agent::llm::providers::copilot::auth::handler::CopilotAuthHandler;
    /// # async fn example(handler: CopilotAuthHandler) -> anyhow::Result<()> {
    /// match handler.try_get_chat_token_silent().await? {
    ///     Some(token) => println!("Got token silently: {}", token),
    ///     None => println!("Need interactive authentication"),
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub async fn try_get_chat_token_silent(&self) -> anyhow::Result<Option<String>> {
        let copilot_token_path = self.app_data_dir.join(".copilot_token.json");

        // Check cached copilot token
        if let Some(cached_config) = self.read_cached_copilot_config(&copilot_token_path) {
            if self.is_copilot_token_valid(&cached_config) {
                return Ok(Some(cached_config.token));
            }
        }

        // Check env var
        if let Ok(token) = std::env::var("COPILOT_API_KEY") {
            let trimmed = token.trim();
            if !trimmed.is_empty() {
                return Ok(Some(trimmed.to_string()));
            }
        }

        // Check access token file and try to exchange
        let token_path = self.app_data_dir.join(".token");
        if let Some(access_token_str) = Self::read_access_token(&token_path) {
            let access_token = AccessTokenResponse::from_token(access_token_str);
            match self.get_copilot_token(access_token).await {
                Ok(copilot_config) => {
                    self.write_cached_copilot_config(&copilot_token_path, &copilot_config)?;
                    return Ok(Some(copilot_config.token));
                }
                Err(e) => {
                    // Only discard the cached access token when we are confident it is invalid.
                    // Copilot tokens are short-lived; the GitHub OAuth access token should be
                    // long-lived, so removing it on transient failures causes unnecessary re-auth.
                    if Self::should_discard_access_token(&e) {
                        let _ = std::fs::remove_file(&token_path);
                    }
                }
            }
        }

        Ok(None)
    }

    /// Force refresh a Copilot token using the cached GitHub OAuth access token.
    ///
    /// This bypasses the `.copilot_token.json` cache and is useful when the cached
    /// Copilot token is rejected early (e.g. revoked) even if it hasn't reached
    /// `expires_at` yet.
    ///
    /// Returns:
    /// - `Ok(Some(token))` if the refresh succeeded
    /// - `Ok(None)` if no cached access token exists
    pub async fn force_refresh_chat_token(&self) -> anyhow::Result<Option<String>> {
        let token_path = self.app_data_dir.join(".token");
        let Some(access_token_str) = Self::read_access_token(&token_path) else {
            return Ok(None);
        };

        let access_token = AccessTokenResponse::from_token(access_token_str);
        match self.get_copilot_token(access_token).await {
            Ok(copilot_config) => {
                let copilot_token_path = self.app_data_dir.join(".copilot_token.json");
                self.write_cached_copilot_config(&copilot_token_path, &copilot_config)?;
                Ok(Some(copilot_config.token))
            }
            Err(e) => {
                if Self::should_discard_access_token(&e) {
                    let _ = std::fs::remove_file(&token_path);
                }
                Err(e)
            }
        }
    }

    fn should_discard_access_token_message(msg: &str) -> bool {
        // get_copilot_token formats errors like:
        // "Copilot token request failed: HTTP {status} - {text}"
        msg.contains("HTTP 401") || msg.contains("HTTP 403")
    }

    fn should_discard_access_token(err: &anyhow::Error) -> bool {
        if err.downcast_ref::<ProxyAuthRequiredError>().is_some() {
            return false;
        }
        Self::should_discard_access_token_message(&err.to_string())
    }

    /// Polls GitHub for an access token after user completes device flow.
    ///
    /// This method continuously polls GitHub's OAuth endpoint until either:
    /// - The user authorizes the application (success)
    /// - The device code expires (error)
    /// - The user denies authorization (error)
    ///
    /// # Polling Behavior
    ///
    /// The method polls at the interval specified in the device code response
    /// (minimum 5 seconds). It handles various OAuth states:
    ///
    /// - `authorization_pending`: User hasn't authorized yet, keep polling
    /// - `slow_down`: Server requested slower polling, increase interval
    /// - `expired_token`: Device code expired, return error
    /// - `access_denied`: User denied authorization, return error
    ///
    /// # Arguments
    ///
    /// * `device_code` - Device code response from [`get_device_code`](Self::get_device_code)
    ///
    /// # Returns
    ///
    /// An [`AccessTokenResponse`] containing the GitHub OAuth access token.
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - Device code expires before user authorizes
    /// - User denies authorization
    /// - Proxy authentication is required
    /// - Network errors occur
    ///
    /// # Display Output
    ///
    /// In headless mode, prints progress dots. In GUI mode, shows polling status.
    pub(super) async fn get_access_token(
        &self,
        device_code: &DeviceCodeResponse,
    ) -> anyhow::Result<AccessTokenResponse> {
        let params = [
            ("client_id", "Iv1.b507a08c87ecfe98"),
            ("device_code", &device_code.device_code),
            ("grant_type", "urn:ietf:params:oauth:grant-type:device_code"),
        ];

        let poll_interval = Duration::from_secs(device_code.interval.max(5));
        let max_duration = Duration::from_secs(device_code.expires_in);
        let start = std::time::Instant::now();

        if !self.headless_auth {
            println!("  🔄 Polling for authorization...");
        }

        loop {
            if start.elapsed() > max_duration {
                return Err(anyhow!("❌ Device code expired. Please try again."));
            }

            let url = format!("{}/login/oauth/access_token", self.github_login_base_url);
            let response = self
                .client
                .post(&url)
                .header("Accept", "application/json")
                .header("User-Agent", "BambooCopilot/1.0")
                .form(&params)
                .send()
                .await?;

            if response.status() == StatusCode::PROXY_AUTHENTICATION_REQUIRED {
                return Err(anyhow!(ProxyAuthRequiredError));
            }

            let response = response.json::<AccessTokenResponse>().await?;

            if let Some(token) = response.access_token {
                if !self.headless_auth {
                    println!("  ✅ Access token received!");
                }
                return Ok(AccessTokenResponse::from_token(token));
            }

            if let Some(error) = &response.error {
                match error.as_str() {
                    "authorization_pending" => {
                        if self.headless_auth {
                            print!(".");
                            std::io::Write::flush(&mut std::io::stdout()).ok();
                        }
                    }
                    "slow_down" => {
                        if !self.headless_auth {
                            println!("\n  ⚠️  Server requested slower polling...");
                        }
                        sleep(Duration::from_secs(device_code.interval + 5)).await;
                        continue;
                    }
                    "expired_token" => {
                        return Err(anyhow!("❌ Device code expired. Please try again."));
                    }
                    "access_denied" => {
                        return Err(anyhow!("❌ Authorization denied by user."));
                    }
                    _ => {
                        let desc = response.error_description.as_deref().unwrap_or("");
                        return Err(anyhow!("❌ Auth error: {} - {}", error, desc));
                    }
                }
            }

            sleep(poll_interval).await;
        }
    }

    /// Exchanges a GitHub access token for a Copilot API token.
    ///
    /// This method exchanges a GitHub OAuth access token for a Copilot-specific
    /// API token by calling GitHub's `/copilot_internal/v2/token` endpoint.
    ///
    /// # Arguments
    ///
    /// * `access_token` - GitHub OAuth access token response
    ///
    /// # Returns
    ///
    /// A [`CopilotConfig`] containing:
    /// - Copilot API token
    /// - Token expiration time
    /// - Feature flags and settings
    /// - API endpoints
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - Access token is invalid or expired
    /// - Copilot is not enabled for the GitHub account
    /// - Proxy authentication is required
    /// - Network errors occur
    /// - Response parsing fails
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// # use bamboo_agent::agent::llm::providers::copilot::auth::handler::{CopilotAuthHandler, AccessTokenResponse};
    /// # async fn example(handler: CopilotAuthHandler, access_token: AccessTokenResponse) -> anyhow::Result<()> {
    /// let config = handler.get_copilot_token(access_token).await?;
    /// println!("Got Copilot token, expires at: {}", config.expires_at);
    /// # Ok(())
    /// # }
    /// ```
    pub(super) async fn get_copilot_token(
        &self,
        access_token: AccessTokenResponse,
    ) -> anyhow::Result<CopilotConfig> {
        let url = format!("{}/copilot_internal/v2/token", self.github_api_base_url);
        let actual_github_token = access_token
            .access_token
            .ok_or_else(|| anyhow!("Access token not found"))?;

        let response = self
            .client
            .get(url)
            .header("Authorization", format!("token {}", actual_github_token))
            .header("Accept", "application/json")
            .header("User-Agent", "BambooCopilot/1.0")
            .send()
            .await?;

        if response.status() == StatusCode::PROXY_AUTHENTICATION_REQUIRED {
            return Err(anyhow!(ProxyAuthRequiredError));
        }

        let status = response.status();
        if !status.is_success() {
            let text = response.text().await.unwrap_or_default();
            return Err(anyhow!(
                "Copilot token request failed: HTTP {} - {}",
                status,
                text
            ));
        }

        let body = response.bytes().await?;
        match serde_json::from_slice::<CopilotConfig>(&body) {
            Ok(copilot_config) => {
                if !copilot_config.chat_enabled {
                    return Err(anyhow!("❌ Copilot chat is not enabled for this account."));
                }
                if !self.headless_auth {
                    println!("  ✅ Copilot token received!");
                }
                Ok(copilot_config)
            }
            Err(_) => {
                let body_str = String::from_utf8_lossy(&body);
                let error_msg = format!("Failed to get copilot config: {body_str}");
                error!("{error_msg}");
                Err(anyhow!(error_msg))
            }
        }
    }
}

/// Integration tests for authentication retry logic.
///
/// These tests verify that authentication requests properly retry
/// on transient failures (e.g., 503 errors) while failing fast
/// on authentication errors (e.g., 401 unauthorized).
#[cfg(test)]
mod retry_tests {
    use super::*;
    use std::sync::atomic::{AtomicUsize, Ordering};
    use std::sync::Mutex as StdMutex;

    // use http; // TODO: add http crate if needed
    use reqwest::Method;
    use reqwest_middleware::{ClientBuilder, Middleware, Next, Result as MiddlewareResult};
    use reqwest_retry::{policies::ExponentialBackoff, RetryTransientMiddleware};

    /// Mock HTTP response for testing.
    #[derive(Clone)]
    struct MockReply {
        /// HTTP status code
        status: u16,
        /// Response body
        body: String,
        /// Content-Type header value
        content_type: Option<&'static str>,
    }

    impl MockReply {
        /// Creates a text response with the given status and body.
        fn text(status: u16, body: impl Into<String>) -> Self {
            Self {
                status,
                body: body.into(),
                content_type: Some("application/json"),
            }
        }

        /// Creates a JSON response with the given status and JSON value.
        fn json(status: u16, value: serde_json::Value) -> Self {
            Self {
                status,
                body: value.to_string(),
                content_type: Some("application/json"),
            }
        }
    }

    /// Middleware that mocks HTTP responses for testing.
    ///
    /// Returns responses in sequence, allowing tests to simulate
    /// retry scenarios (e.g., return 503 twice, then 200).
    #[derive(Clone)]
    struct MockResponder {
        /// Expected HTTP method
        expected_method: Method,
        /// Expected URL path
        expected_path: String,
        /// Counter for number of calls
        call_count: Arc<AtomicUsize>,
        /// Queue of responses to return
        replies: Arc<StdMutex<Vec<MockReply>>>,
    }

    impl MockResponder {
        /// Creates a new mock responder.
        ///
        /// # Arguments
        ///
        /// * `expected_method` - HTTP method to expect
        /// * `expected_path` - URL path to expect
        /// * `call_count` - Counter to track number of calls
        /// * `replies` - Queue of responses to return in sequence
        fn new(
            expected_method: Method,
            expected_path: impl Into<String>,
            call_count: Arc<AtomicUsize>,
            replies: Vec<MockReply>,
        ) -> Self {
            Self {
                expected_method,
                expected_path: expected_path.into(),
                call_count,
                replies: Arc::new(StdMutex::new(replies)),
            }
        }
    }

    #[async_trait::async_trait]
    impl Middleware for MockResponder {
        async fn handle(
            &self,
            req: reqwest::Request,
            _extensions: &mut http::Extensions,
            _next: Next<'_>,
        ) -> MiddlewareResult<reqwest::Response> {
            assert_eq!(
                req.method(),
                &self.expected_method,
                "unexpected method for {}",
                req.url()
            );
            assert_eq!(
                req.url().path(),
                self.expected_path.as_str(),
                "unexpected path for {}",
                req.url()
            );

            let idx = self.call_count.fetch_add(1, Ordering::SeqCst);
            let reply = {
                let mut guard = self.replies.lock().expect("lock");
                if guard.is_empty() {
                    panic!("no mock reply left for call #{idx}");
                }
                guard.remove(0)
            };

            let mut builder = http::Response::builder().status(reply.status);
            if let Some(ct) = reply.content_type {
                builder = builder.header("content-type", ct);
            }

            let http_response = builder.body(reply.body).expect("http response");
            Ok(reqwest::Response::from(http_response))
        }
    }

    /// Creates a test HTTP client with retry middleware and mock responder.
    fn create_test_client_with_retry(mock: MockResponder) -> Arc<ClientWithMiddleware> {
        use reqwest::Client as ReqwestClient;

        // Use a zero-delay retry policy to keep tests fast and deterministic.
        let retry_policy = ExponentialBackoff::builder()
            .retry_bounds(Duration::from_millis(0), Duration::from_millis(0))
            .build_with_max_retries(3);

        let client = ReqwestClient::builder().build().expect("client");

        Arc::new(
            ClientBuilder::new(client)
                .with(RetryTransientMiddleware::new_with_policy(retry_policy))
                .with(mock)
                .build(),
        )
    }

    /// Creates a sample CopilotConfig for testing with specified expiration time.
    fn sample_config(expires_at: u64) -> CopilotConfig {
        CopilotConfig {
            token: "cached-token".to_string(),
            annotations_enabled: false,
            chat_enabled: true,
            chat_jetbrains_enabled: false,
            code_quote_enabled: false,
            code_review_enabled: false,
            codesearch: false,
            copilotignore_enabled: false,
            endpoints: Endpoints {
                api: Some("https://api.example.com".to_string()),
                origin_tracker: None,
                proxy: None,
                telemetry: None,
            },
            expires_at,
            individual: true,
            limited_user_quotas: None,
            limited_user_reset_date: None,
            prompt_8k: false,
            public_suggestions: "disabled".to_string(),
            refresh_in: 300,
            sku: "test".to_string(),
            snippy_load_test_enabled: false,
            telemetry: "disabled".to_string(),
            tracking_id: "test".to_string(),
            vsc_electron_fetcher_v2: false,
            xcode: false,
            xcode_chat: false,
        }
    }

    /// Test that auth requests are retried on transient failures.
    ///
    /// Simulates a scenario where the Copilot token endpoint returns
    /// 503 (Service Unavailable) twice before succeeding. Verifies that:
    /// - The request is retried automatically
    /// - Eventually succeeds after retries
    /// - Total call count is 3 (2 failures + 1 success)
    #[tokio::test]
    async fn test_auth_retry_on_server_error() {
        let request_count = Arc::new(AtomicUsize::new(0));

        let mock = MockResponder::new(
            Method::GET,
            "/copilot_internal/v2/token",
            request_count.clone(),
            vec![
                MockReply::text(503, r#"{"error":"Service Unavailable"}"#),
                MockReply::text(503, r#"{"error":"Service Unavailable"}"#),
                MockReply::json(
                    200,
                    serde_json::json!({
                        "token": "test-copilot-token",
                        "expires_at": (SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_secs() + 3600),
                        "annotations_enabled": true,
                        "chat_enabled": true,
                        "chat_jetbrains_enabled": false,
                        "code_quote_enabled": true,
                        "code_review_enabled": false,
                        "codesearch": false,
                        "copilotignore_enabled": true,
                        "endpoints": {
                            "api": "https://api.githubcopilot.com"
                        },
                        "individual": true,
                        "prompt_8k": true,
                        "public_suggestions": "disabled",
                        "refresh_in": 300,
                        "sku": "copilot_individual",
                        "snippy_load_test_enabled": false,
                        "telemetry": "disabled",
                        "tracking_id": "test-tracking-id",
                        "vsc_electron_fetcher_v2": true,
                        "xcode": false,
                        "xcode_chat": false
                    }),
                ),
            ],
        );

        let client = create_test_client_with_retry(mock);
        let temp_dir = tempfile::tempdir().expect("tempdir");
        let handler = CopilotAuthHandler::new(client, temp_dir.path().to_path_buf(), true)
            .with_github_api_base_url("http://mock.local");

        // Create a valid access token
        let access_token = AccessTokenResponse {
            access_token: Some("test-github-token".to_string()),
            token_type: Some("bearer".to_string()),
            scope: Some("read:user".to_string()),
            error: None,
            error_description: None,
        };

        // This should retry and eventually succeed
        let result = handler.get_copilot_token(access_token).await;
        assert!(
            result.is_ok(),
            "Should succeed after retries: {:?}",
            result.err()
        );
        assert_eq!(request_count.load(Ordering::SeqCst), 3);

        let config = result.unwrap();
        assert_eq!(config.token, "test-copilot-token");
    }

    /// Test that auth requests fail fast on 401 (no retry).
    ///
    /// Verifies that authentication errors (401 Unauthorized) are not
    /// retried, as retrying would not fix the underlying issue.
    #[tokio::test]
    async fn test_auth_no_retry_on_unauthorized() {
        let request_count = Arc::new(AtomicUsize::new(0));

        let mock = MockResponder::new(
            Method::GET,
            "/copilot_internal/v2/token",
            request_count.clone(),
            vec![MockReply::text(401, r#"{"error":"Unauthorized"}"#)],
        );

        let client = create_test_client_with_retry(mock);
        let temp_dir = tempfile::tempdir().expect("tempdir");
        let handler = CopilotAuthHandler::new(client, temp_dir.path().to_path_buf(), true)
            .with_github_api_base_url("http://mock.local");

        let access_token = AccessTokenResponse {
            access_token: Some("invalid-token".to_string()),
            token_type: Some("bearer".to_string()),
            scope: Some("read:user".to_string()),
            error: None,
            error_description: None,
        };

        let result = handler.get_copilot_token(access_token).await;
        assert!(result.is_err());
        assert_eq!(request_count.load(Ordering::SeqCst), 1);
    }

    /// Test device code endpoint retry.
    ///
    /// Simulates transient failures when requesting a device code
    /// and verifies that the request is retried until success.
    #[tokio::test]
    async fn test_device_code_retry() {
        let request_count = Arc::new(AtomicUsize::new(0));

        let mock = MockResponder::new(
            Method::POST,
            "/login/device/code",
            request_count.clone(),
            vec![
                MockReply::text(503, ""),
                MockReply::text(503, ""),
                MockReply::json(
                    200,
                    serde_json::json!({
                        "device_code": "test-device-code",
                        "user_code": "ABCD-EFGH",
                        "verification_uri": "https://github.com/login/device",
                        "expires_in": 900,
                        "interval": 5
                    }),
                ),
            ],
        );

        let client = create_test_client_with_retry(mock);
        let temp_dir = tempfile::tempdir().expect("tempdir");
        let handler = CopilotAuthHandler::new(client, temp_dir.path().to_path_buf(), true)
            .with_github_login_base_url("http://mock.local");

        // Call the actual method - it should retry and eventually succeed
        let result = handler.get_device_code().await;

        assert!(
            result.is_ok(),
            "Should succeed after retries: {:?}",
            result.err()
        );
        assert_eq!(request_count.load(Ordering::SeqCst), 3);

        let device_code = result.unwrap();
        assert_eq!(device_code.device_code, "test-device-code");
        assert_eq!(device_code.user_code, "ABCD-EFGH");
    }

    /// Test token cache validation.
    ///
    /// Verifies that the 60-second buffer for token validation works correctly:
    /// - Tokens valid for > 60 seconds are considered valid
    /// - Tokens expired or expiring within 60 seconds are considered invalid
    #[test]
    fn test_token_cache_validation() {
        let temp_dir = tempfile::tempdir().expect("tempdir");
        let client = create_test_client_with_retry(MockResponder::new(
            Method::GET,
            "/__unused__",
            Arc::new(AtomicUsize::new(0)),
            vec![],
        ));
        let handler = CopilotAuthHandler::new(client, temp_dir.path().to_path_buf(), true);

        // Valid token (expires in 1 hour)
        let valid_config = sample_config(
            SystemTime::now()
                .duration_since(UNIX_EPOCH)
                .unwrap()
                .as_secs()
                + 3600,
        );
        assert!(handler.is_copilot_token_valid(&valid_config));

        // Expired token (expired 1 hour ago)
        let expired_config = sample_config(
            SystemTime::now()
                .duration_since(UNIX_EPOCH)
                .unwrap()
                .as_secs()
                - 3600,
        );
        assert!(!handler.is_copilot_token_valid(&expired_config));

        // Token expiring soon (30 seconds left, but we use 60s buffer)
        let expiring_soon_config = sample_config(
            SystemTime::now()
                .duration_since(UNIX_EPOCH)
                .unwrap()
                .as_secs()
                + 30,
        );
        assert!(!handler.is_copilot_token_valid(&expiring_soon_config));
    }

    /// Test cached config round-trip with retry client.
    ///
    /// Verifies that CopilotConfig can be written to disk and read back
    /// correctly when using an HTTP client with retry middleware.
    #[test]
    fn test_cached_copilot_config_with_retry_client() {
        let dir = tempfile::tempdir().expect("tempdir");
        let client = create_test_client_with_retry(MockResponder::new(
            Method::GET,
            "/__unused__",
            Arc::new(AtomicUsize::new(0)),
            vec![],
        ));
        let handler = CopilotAuthHandler::new(client, dir.path().to_path_buf(), false);
        let token_path = dir.path().join(".copilot_token.json");

        let expires_at = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_secs()
            + 3600;
        let config = sample_config(expires_at);

        handler
            .write_cached_copilot_config(&token_path, &config)
            .expect("write cache");
        let loaded = handler
            .read_cached_copilot_config(&token_path)
            .expect("read cache");

        assert_eq!(loaded.token, config.token);
        assert_eq!(loaded.expires_at, config.expires_at);
    }
}