cargo-port 0.1.3

A TUI for inspecting and managing Rust projects
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
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
//! Direct HTTP client for GitHub and crates.io APIs.
//!
//! Uses `reqwest` (async) backed by a `tokio` runtime for concurrent
//! HTTP. Sync wrappers (`handle.block_on`) are provided for callers
//! that run on std/rayon threads during TUI startup and background work.

mod constants;
mod rate_limit;

use std::collections::HashMap;
use std::fmt::Write;
use std::io;
use std::io::ErrorKind;
use std::process::Command;
use std::process::Output;
use std::sync::Arc;
use std::sync::Mutex;
use std::sync::atomic::AtomicBool;
use std::sync::atomic::AtomicU64;
use std::sync::atomic::Ordering;
use std::time::Duration;

use chrono::Utc;
pub(crate) use rate_limit::GitHubRateLimit;
pub(crate) use rate_limit::RateLimitBucket;
pub(crate) use rate_limit::RateLimitQuota;
use rate_limit::SYNTHETIC_RATE_LIMIT_SECS;
use rate_limit::classify_network_error;
pub(crate) use rate_limit::github_is_rate_limited;
pub(crate) use rate_limit::graphql_body_is_rate_limited;
use rate_limit::now_epoch_secs;
pub(crate) use rate_limit::parse_rate_limit_headers;
pub(crate) use rate_limit::parse_rate_limit_response;
use reqwest::Client;
use reqwest::Error;
use serde::Deserialize;
use serde_json::Value;
use tokio::runtime::Handle;

use self::constants::ACCEPT_HEADER;
use self::constants::AUTHORIZATION_HEADER;
use self::constants::CONTENT_TYPE_HEADER;
use self::constants::CRATES_IO_CRATE_KEY;
use self::constants::CRATES_IO_DOWNLOADS_KEY;
use self::constants::CRATES_IO_MAX_STABLE_VERSION_KEY;
use self::constants::CRATES_IO_MAX_VERSION_KEY;
use self::constants::GITHUB_GRAPHQL_DATA_KEY;
use self::constants::GITHUB_GRAPHQL_DESCRIPTION_KEY;
use self::constants::GITHUB_GRAPHQL_REPO_KEY;
use self::constants::GITHUB_GRAPHQL_RUN_ALIAS_PREFIX;
use self::constants::GITHUB_GRAPHQL_STARGAZER_COUNT_KEY;
use self::constants::GITHUB_JSON_MEDIA_TYPE;
use self::constants::GITHUB_PR_PAGE_CAP;
use self::constants::GITHUB_PR_PAGE_SIZE;
use self::constants::JSON_MEDIA_TYPE;
use self::constants::USER_AGENT_HEADER;
use super::ci::GhRun;
use super::ci::GqlCheckRun;
use super::ci::OwnerRepo;
use super::constants::APP_NAME;
use super::constants::CRATES_IO_API_BASE;
use super::constants::CRATES_IO_USER_AGENT;
use super::constants::GH_TIMEOUT;
use super::constants::GITHUB_API_BASE;
use super::constants::GITHUB_GRAPHQL_URL;
use super::constants::SERVICE_RETRY_SECS;
use super::project::ProjectPrInfo;
use super::project::PullRequestCompleteness;
use super::project::PullRequestGoneReason;
use super::project::PullRequestInfo;
use super::project::PullRequestState;
use super::project::PullRequestUnavailableReason;
use super::scan::CratesIoInfo;
use super::scan::RepoMetaInfo;

#[derive(Clone, Copy, Debug, Hash, PartialEq, Eq)]
pub(crate) enum ServiceKind {
    GitHub,
    CratesIo,
}

impl ServiceKind {
    const fn probe_url(self) -> &'static str {
        match self {
            Self::GitHub => GITHUB_API_BASE,
            Self::CratesIo => CRATES_IO_API_BASE,
        }
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum ServiceSignal {
    Reachable(ServiceKind),
    /// The service is unreachable over the network (DNS failure,
    /// connection refused, timeout, 5xx). Distinct from `RateLimited`
    /// because the recovery path and user-facing message differ.
    Unreachable(ServiceKind),
    /// The service is reachable but refusing our requests with a
    /// rate-limit status (GitHub 429, 403 + `X-RateLimit-Remaining: 0`,
    /// or GraphQL body `errors[].type == "RATE_LIMITED"`). The display
    /// buckets can still refresh via the quota-exempt `/rate_limit`
    /// endpoint.
    RateLimited(ServiceKind),
}

type GitHubJobsAndMeta = (HashMap<u64, Vec<GqlCheckRun>>, Option<RepoMetaInfo>);

pub(crate) type HttpOutcome<T> = (Option<T>, Option<ServiceSignal>);

// ── Serde types for API responses ────────────────────────────────────

#[derive(Deserialize)]
struct GhRunsResponse {
    total_count:   u32,
    workflow_runs: Vec<GhRun>,
}

/// Workflow runs plus the total count reported by GitHub.
pub(crate) struct GhRunsList {
    pub runs:        Vec<GhRun>,
    pub total_count: u32,
}

pub(crate) enum PullRequestFetch {
    Loaded(ProjectPrInfo),
    Unavailable(PullRequestUnavailableReason),
}

type PullRequestPages = Result<
    (Vec<GqlPullRequestNode>, String, PullRequestCompleteness),
    PullRequestUnavailableReason,
>;

#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct GqlRunNode {
    database_id: u64,
    check_suite: Option<GqlCheckSuite>,
}

#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct GqlCheckSuite {
    check_runs: GqlCheckRunConnection,
}

#[derive(Deserialize)]
struct GqlCheckRunConnection {
    nodes: Vec<GqlCheckRun>,
}

#[derive(Deserialize)]
struct GqlViewerResponse {
    data:   Option<GqlViewerData>,
    errors: Option<Vec<Value>>,
}

#[derive(Deserialize)]
struct GqlViewerData {
    viewer: GqlViewer,
}

#[derive(Deserialize)]
struct GqlViewer {
    login: String,
}

#[derive(Deserialize)]
struct GqlPullRequestsResponse {
    data:   Option<GqlPullRequestsData>,
    errors: Option<Vec<Value>>,
}

#[derive(Deserialize)]
struct GqlPullRequestsData {
    repository: Option<GqlPullRequestRepository>,
    search:     Option<GqlPullRequestSearch>,
}

#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct GqlPullRequestRepository {
    default_branch_ref: Option<GqlBranchRef>,
}

#[derive(Deserialize)]
struct GqlBranchRef {
    name: String,
}

#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct GqlPullRequestSearch {
    page_info: GqlPageInfo,
    nodes:     Vec<Option<GqlPullRequestNode>>,
}

#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct GqlPageInfo {
    has_next_page: bool,
    end_cursor:    Option<String>,
}

#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct GqlPullRequestNode {
    number:             u32,
    title:              String,
    url:                String,
    is_draft:           bool,
    review_decision:    Option<String>,
    merge_state_status: Option<String>,
    head_ref_name:      String,
    base_ref_name:      String,
    head_repository:    Option<GqlPullRequestHeadRepository>,
}

#[derive(Deserialize)]
struct GqlPullRequestHeadRepository {
    name:  String,
    owner: GqlRepositoryOwner,
}

#[derive(Deserialize)]
struct GqlRepositoryOwner {
    login: String,
}

#[derive(Deserialize)]
struct GqlPullRequestStatusResponse {
    data:   Option<GqlPullRequestStatusData>,
    errors: Option<Vec<Value>>,
}

#[derive(Deserialize)]
struct GqlPullRequestStatusData {
    repository: Option<GqlPullRequestStatusRepository>,
}

#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct GqlPullRequestStatusRepository {
    pull_request: Option<GqlPullRequestStatusNode>,
}

#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct GqlPullRequestStatusNode {
    merged:        bool,
    closed:        bool,
    base_ref_name: String,
}

const fn unavailable_reason_from_signal(
    signal: Option<ServiceSignal>,
) -> PullRequestUnavailableReason {
    match signal {
        Some(ServiceSignal::RateLimited(ServiceKind::GitHub)) => {
            PullRequestUnavailableReason::RateLimited
        },
        Some(ServiceSignal::Unreachable(ServiceKind::GitHub)) => {
            PullRequestUnavailableReason::Network
        },
        _ => PullRequestUnavailableReason::GraphQlError,
    }
}

const fn combine_optional_signal(
    left: Option<ServiceSignal>,
    right: Option<ServiceSignal>,
) -> Option<ServiceSignal> {
    match (left, right) {
        (Some(ServiceSignal::Unreachable(service)), _)
        | (_, Some(ServiceSignal::Unreachable(service))) => {
            Some(ServiceSignal::Unreachable(service))
        },
        (Some(ServiceSignal::RateLimited(service)), _)
        | (_, Some(ServiceSignal::RateLimited(service))) => {
            Some(ServiceSignal::RateLimited(service))
        },
        (Some(ServiceSignal::Reachable(service)), _)
        | (_, Some(ServiceSignal::Reachable(service))) => Some(ServiceSignal::Reachable(service)),
        (None, None) => None,
    }
}

fn graphql_string(value: &str) -> String {
    serde_json::to_string(value).unwrap_or_else(|_| "\"\"".to_string())
}

fn pull_requests_query(
    owner: &str,
    repo: &str,
    search_query: &str,
    cursor: Option<&str>,
) -> String {
    let owner = graphql_string(owner);
    let repo = graphql_string(repo);
    let search_query = graphql_string(search_query);
    let after = cursor.map_or_else(String::new, |cursor| {
        format!(", after: {}", graphql_string(cursor))
    });
    format!(
        "{{ repository(owner: {owner}, name: {repo}) {{ defaultBranchRef {{ name }} }} \
         search(type: ISSUE, first: {GITHUB_PR_PAGE_SIZE}{after}, query: {search_query}) \
         {{ pageInfo {{ hasNextPage endCursor }} nodes {{ ... on PullRequest {{ number title url \
         isDraft reviewDecision mergeStateStatus headRefName baseRefName \
         headRepository {{ name owner {{ login }} }} }} }} }} }}"
    )
}

fn pull_request_status_query(owner: &str, repo: &str, number: u32) -> String {
    let owner = graphql_string(owner);
    let repo = graphql_string(repo);
    format!(
        "{{ repository(owner: {owner}, name: {repo}) {{ pullRequest(number: {number}) \
         {{ merged closed baseRefName }} }} }}"
    )
}

fn build_project_pr_info(
    owner_repo: OwnerRepo,
    viewer_login: String,
    default_branch: String,
    nodes: Vec<GqlPullRequestNode>,
    completeness: PullRequestCompleteness,
) -> ProjectPrInfo {
    ProjectPrInfo {
        open: nodes.into_iter().map(pull_request_info_from_node).collect(),
        default_branch,
        fetched_at: Utc::now().format("%+").to_string(),
        completeness,
        viewer_login,
        owner_repo,
    }
}

fn pull_request_info_from_node(node: GqlPullRequestNode) -> PullRequestInfo {
    let state = reduce_pull_request_state(
        node.is_draft,
        node.review_decision.as_deref(),
        node.merge_state_status.as_deref(),
    );
    PullRequestInfo {
        number: node.number,
        title: node.title,
        url: node.url,
        state,
        head: node.head_ref_name,
        head_owner: node
            .head_repository
            .as_ref()
            .map(|repo| repo.owner.login.clone()),
        head_repo: node.head_repository.map(|repo| repo.name),
        base: node.base_ref_name,
    }
}

fn reduce_pull_request_state(
    is_draft: bool,
    review_decision: Option<&str>,
    merge_state_status: Option<&str>,
) -> PullRequestState {
    if is_draft {
        return PullRequestState::Draft;
    }
    if review_decision == Some("CHANGES_REQUESTED") {
        return PullRequestState::ChangesRequested;
    }
    match merge_state_status {
        Some("UNSTABLE") => return PullRequestState::ChecksFailing,
        Some("BLOCKED" | "DIRTY" | "HAS_HOOKS") => return PullRequestState::Blocked,
        Some("BEHIND") => return PullRequestState::Behind,
        _ => {},
    }
    match review_decision {
        Some("REVIEW_REQUIRED") => PullRequestState::ReviewRequired,
        Some("APPROVED") => PullRequestState::Approved,
        _ => match merge_state_status {
            Some("CLEAN") | None => PullRequestState::Ready,
            Some(_) => PullRequestState::Unknown,
        },
    }
}

// ── Client ───────────────────────────────────────────────────────────

/// Shared HTTP client backed by `reqwest::Client` for connection
/// pooling and async I/O. `Clone` is cheap — the underlying client uses
/// `Arc`. A `tokio::runtime::Handle` is stored so sync callers can
/// dispatch async work via `block_on`.
#[derive(Clone)]
pub(crate) struct HttpClient {
    client:                  Client,
    github_auth:             GithubAuth,
    github_viewer_login:     Arc<Mutex<Option<String>>>,
    rate_limit:              Arc<Mutex<GitHubRateLimit>>,
    /// When true, every GitHub REST + GraphQL call (and the recovery
    /// probe) short-circuits to a synthetic rate-limited outcome so the
    /// rate-limit UI and toast flow can be exercised deterministically.
    /// `/rate_limit` itself stays real — the display must keep ticking.
    force_github_rate_limit: Arc<AtomicBool>,
    /// Epoch-seconds reset timestamp used to drive the synthetic
    /// core-bucket countdown while `force_github_rate_limit` is on. `0`
    /// means "not set". Rebased on every off→on transition so the
    /// countdown starts at `00:59:59` and ticks down from there.
    force_reset_at:          Arc<AtomicU64>,
    pub(crate) handle:       Handle,
}

/// Result of the one-shot `gh auth token` probe run at startup. Holds the
/// token when authenticated; otherwise records *why* there is no token so
/// the UI can give the right remediation — install `gh` versus run `gh
/// auth login`. Keeping token and reason in one enum makes the "token
/// present but `gh` missing" combination unrepresentable.
#[derive(Clone)]
enum GithubAuth {
    Authenticated(String),
    /// `gh` ran but returned no token (the user is not logged in).
    Unauthenticated,
    /// The `gh` binary was not found on `PATH`.
    NotInstalled,
}

impl GithubAuth {
    /// Classify the outcome of the startup `gh auth token` probe. A
    /// success exit yields the trimmed token — or `Unauthenticated` when
    /// stdout is not valid UTF-8. A spawn error of kind `NotFound` means
    /// the `gh` binary is absent; every other outcome (non-success exit,
    /// other spawn errors) is treated as logged-out.
    fn classify(output: io::Result<Output>) -> Self {
        match output {
            Ok(output) if output.status.success() => String::from_utf8(output.stdout)
                .map_or(Self::Unauthenticated, |token| {
                    Self::Authenticated(token.trim().to_string())
                }),
            Err(error) if error.kind() == ErrorKind::NotFound => Self::NotInstalled,
            Ok(_) | Err(_) => Self::Unauthenticated,
        }
    }

    /// The bearer token when authenticated; `None` for either gap.
    const fn token(&self) -> Option<&str> {
        match self {
            Self::Authenticated(token) => Some(token.as_str()),
            Self::Unauthenticated | Self::NotInstalled => None,
        }
    }

    /// Projects the auth state to the gap the UI surfaces, dropping the
    /// token. `None` means authenticated — there is nothing to warn about.
    const fn gap(&self) -> Option<GithubAuthGap> {
        match self {
            Self::Authenticated(_) => None,
            Self::Unauthenticated => Some(GithubAuthGap::Unauthenticated),
            Self::NotInstalled => Some(GithubAuthGap::NotInstalled),
        }
    }
}

/// Why GitHub calls are disabled, surfaced to the UI so the startup toast
/// and git-pane row give the right remediation. Excludes the authenticated
/// case — there is no gap to report.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum GithubAuthGap {
    /// The `gh` binary was not found on `PATH`.
    NotInstalled,
    /// `gh` is installed but returned no token.
    Unauthenticated,
}

impl HttpClient {
    /// Build a new client. Obtains the GitHub auth token from `gh auth
    /// token` (single subprocess call). If `gh` is unavailable or not
    /// authenticated, GitHub API methods degrade gracefully.
    pub(crate) fn new(handle: Handle) -> Option<Self> {
        let client = build_client().ok()?;
        let github_auth = GithubAuth::classify(Command::new("gh").args(["auth", "token"]).output());
        Some(Self {
            client,
            github_auth,
            github_viewer_login: Arc::new(Mutex::new(None)),
            rate_limit: Arc::new(Mutex::new(GitHubRateLimit::default())),
            force_github_rate_limit: Arc::new(AtomicBool::new(false)),
            force_reset_at: Arc::new(AtomicU64::new(0)),
            handle,
        })
    }

    /// Whether a GitHub auth token was obtained at construction. When
    /// false, every authenticated REST / GraphQL call short-circuits to
    /// a no-op (see `github_get_async` / `github_graphql_async`), so CI
    /// runs and rate-limit buckets never load.
    pub(crate) const fn has_github_token(&self) -> bool {
        matches!(self.github_auth, GithubAuth::Authenticated(_))
    }

    /// The GitHub auth gap to surface at startup, or `None` when a token
    /// was obtained. Drives the startup toast copy and the git-pane row.
    pub(crate) const fn github_auth_gap(&self) -> Option<GithubAuthGap> { self.github_auth.gap() }

    /// Toggle the synthetic GitHub rate-limit short-circuit at runtime.
    /// Intended for the `[debug] force_github_rate_limit` config flag.
    /// Turning the flag on rebases the synthetic countdown to
    /// `now + SYNTHETIC_RATE_LIMIT_SECS` so the display starts at
    /// `00:59:59` and counts down from there.
    pub(crate) fn set_force_github_rate_limit(&self, on: bool) {
        self.force_github_rate_limit.store(on, Ordering::Relaxed);
        if on {
            let reset_at = now_epoch_secs().saturating_add(SYNTHETIC_RATE_LIMIT_SECS);
            self.force_reset_at.store(reset_at, Ordering::Relaxed);
        } else {
            self.force_reset_at.store(0, Ordering::Relaxed);
        }
    }

    fn github_rate_limit_forced(&self) -> bool {
        self.force_github_rate_limit.load(Ordering::Relaxed)
    }

    fn synthetic_core_quota(&self) -> RateLimitQuota {
        let reset_at = self.force_reset_at.load(Ordering::Relaxed);
        RateLimitQuota {
            limit:     5000,
            used:      5000,
            remaining: 0,
            reset_at:  if reset_at == 0 { None } else { Some(reset_at) },
        }
    }

    /// the current live rate-limit state. Returned by value —
    /// `GitHubRateLimit` is `Copy`. While `force_github_rate_limit` is
    /// on, the `core` bucket is overridden with a synthetic `0/5000`
    /// reading whose reset timestamp is stable so the countdown ticks
    /// down instead of oscillating. `graphql` stays real so the
    /// live-refresh behaviour of the `/rate_limit` endpoint is still
    /// visible during debug.
    pub(crate) fn rate_limit(&self) -> GitHubRateLimit {
        let real = self
            .rate_limit
            .lock()
            .map(|state| *state)
            .unwrap_or_default();
        if self.github_rate_limit_forced() {
            return GitHubRateLimit {
                core:    Some(self.synthetic_core_quota()),
                graphql: real.graphql,
            };
        }
        real
    }

    fn update_rate_limit_bucket(&self, bucket: RateLimitBucket, quota: RateLimitQuota) {
        let Ok(mut state) = self.rate_limit.lock() else {
            return;
        };
        match bucket {
            RateLimitBucket::Core => state.core = Some(quota),
            RateLimitBucket::GraphQl => state.graphql = Some(quota),
        }
    }

    fn set_rate_limit(&self, github_rate_limit: GitHubRateLimit) {
        if let Ok(mut state) = self.rate_limit.lock() {
            *state = github_rate_limit;
        }
    }

    // ── Async internals ─────────────────────────────────────────────

    async fn github_get_async(&self, path: &str) -> HttpOutcome<Vec<u8>> {
        if self.github_rate_limit_forced() {
            return (None, Some(ServiceSignal::RateLimited(ServiceKind::GitHub)));
        }
        let Some(token) = self.github_auth.token() else {
            return (None, None);
        };
        let url = format!("{GITHUB_API_BASE}/{path}");
        let response = match self
            .client
            .get(&url)
            .header(AUTHORIZATION_HEADER, format!("Bearer {token}"))
            .header(ACCEPT_HEADER, GITHUB_JSON_MEDIA_TYPE)
            .send()
            .await
        {
            Ok(response) => response,
            Err(error) => return (None, classify_network_error(ServiceKind::GitHub, &error)),
        };
        if let Some((bucket, quota)) = parse_rate_limit_headers(response.headers()) {
            self.update_rate_limit_bucket(bucket, quota);
        }
        let status = response.status();
        let rate_limited = github_is_rate_limited(status, response.headers());
        let body = match response.bytes().await {
            Ok(body) => body,
            Err(error) => {
                return (
                    None,
                    classify_network_error(ServiceKind::GitHub, &error)
                        .or(Some(ServiceSignal::Reachable(ServiceKind::GitHub))),
                );
            },
        };
        if rate_limited {
            return (None, Some(ServiceSignal::RateLimited(ServiceKind::GitHub)));
        }
        (
            Some(body.to_vec()),
            Some(ServiceSignal::Reachable(ServiceKind::GitHub)),
        )
    }

    async fn github_graphql_async(&self, query: &str) -> HttpOutcome<Vec<u8>> {
        if self.github_rate_limit_forced() {
            return (None, Some(ServiceSignal::RateLimited(ServiceKind::GitHub)));
        }
        let Some(token) = self.github_auth.token() else {
            return (None, None);
        };
        let payload = serde_json::json!({ "query": query });
        let response = match self
            .client
            .post(GITHUB_GRAPHQL_URL)
            .header(AUTHORIZATION_HEADER, format!("Bearer {token}"))
            .header(CONTENT_TYPE_HEADER, JSON_MEDIA_TYPE)
            .body(payload.to_string())
            .send()
            .await
        {
            Ok(response) => response,
            Err(error) => return (None, classify_network_error(ServiceKind::GitHub, &error)),
        };
        if let Some((bucket, quota)) = parse_rate_limit_headers(response.headers()) {
            self.update_rate_limit_bucket(bucket, quota);
        }
        let status = response.status();
        let http_rate_limited = github_is_rate_limited(status, response.headers());
        let body = match response.bytes().await {
            Ok(body) => body,
            Err(error) => {
                return (
                    None,
                    classify_network_error(ServiceKind::GitHub, &error)
                        .or(Some(ServiceSignal::Reachable(ServiceKind::GitHub))),
                );
            },
        };
        if http_rate_limited {
            return (None, Some(ServiceSignal::RateLimited(ServiceKind::GitHub)));
        }
        // GraphQL returns HTTP 200 on rate-limit, so status-code
        // detection alone is insufficient — inspect the body's
        // `errors[].type` for `RATE_LIMITED`.
        if let Ok(json) = serde_json::from_slice::<serde_json::Value>(&body)
            && graphql_body_is_rate_limited(&json)
        {
            return (None, Some(ServiceSignal::RateLimited(ServiceKind::GitHub)));
        }
        (
            Some(body.to_vec()),
            Some(ServiceSignal::Reachable(ServiceKind::GitHub)),
        )
    }

    // ── Async public API ────────────────────────────────────────────

    /// List recent completed workflow runs for a repo (async).
    pub(crate) async fn list_runs_async(
        &self,
        owner: &str,
        repo: &str,
        branch: Option<&str>,
        count: u32,
        created_before: Option<&str>,
    ) -> HttpOutcome<GhRunsList> {
        let mut path =
            format!("repos/{owner}/{repo}/actions/runs?per_page={count}&status=completed");
        if let Some(branch) = branch {
            let _ = write!(path, "&branch={branch}");
        }
        // ISO 8601 timestamp from CiRun.created_at — strict less-than.
        if let Some(date) = created_before {
            let _ = write!(path, "&created=<{date}");
        }
        let (body, signal) = self.github_get_async(&path).await;
        let value = body.and_then(|body| {
            serde_json::from_slice::<GhRunsResponse>(&body)
                .ok()
                .map(|response| GhRunsList {
                    runs:        response.workflow_runs,
                    total_count: response.total_count,
                })
        });
        (value, signal)
    }

    /// Batch-fetch job details for uncached runs AND repo metadata in a
    /// single GraphQL call (async). Returns jobs map + optional repo
    /// metadata.
    pub(crate) async fn batch_fetch_jobs_and_meta_async(
        &self,
        owner: &str,
        repo: &str,
        runs: &[&GhRun],
    ) -> HttpOutcome<GitHubJobsAndMeta> {
        let repo_fragment = format!(
            "repo: repository(owner: \"{owner}\", name: \"{repo}\") {{ stargazerCount description }}"
        );

        let run_fragment = "checkSuite { checkRuns(first: 50) { nodes { \
                            name conclusion startedAt completedAt } } }";

        let mut parts = vec![repo_fragment];
        for (i, run) in runs.iter().enumerate() {
            parts.push(format!(
                "run_{i}: node(id: \"{}\") \
                 {{ ... on WorkflowRun {{ databaseId {run_fragment} }} }}",
                run.node_id
            ));
        }

        let query = format!("{{ {} }}", parts.join(" "));
        let (body, signal) = self.github_graphql_async(&query).await;
        let Some(body) = body else {
            return (None, signal);
        };
        let Ok(json) = serde_json::from_slice::<serde_json::Value>(&body) else {
            return (None, signal);
        };
        let Some(data) = json.get(GITHUB_GRAPHQL_DATA_KEY) else {
            return (None, signal);
        };

        // Parse repo metadata.
        let meta = data.get(GITHUB_GRAPHQL_REPO_KEY).and_then(|r| {
            let stars = r.get(GITHUB_GRAPHQL_STARGAZER_COUNT_KEY)?.as_u64()?;
            let description = r
                .get(GITHUB_GRAPHQL_DESCRIPTION_KEY)
                .and_then(serde_json::Value::as_str)
                .filter(|s| !s.is_empty())
                .map(String::from);
            Some(RepoMetaInfo { stars, description })
        });

        // Parse run nodes.
        let jobs = data
            .as_object()
            .map(|obj| {
                obj.iter()
                    .filter(|(key, _)| key.starts_with(GITHUB_GRAPHQL_RUN_ALIAS_PREFIX))
                    .filter_map(|(_, val)| {
                        let node: GqlRunNode = serde_json::from_value(val.clone()).ok()?;
                        let check_runs = node.check_suite?.check_runs.nodes;
                        Some((node.database_id, check_runs))
                    })
                    .collect()
            })
            .unwrap_or_default();

        (Some((jobs, meta)), signal)
    }

    async fn github_viewer_login_async(
        &self,
    ) -> HttpOutcome<Result<String, PullRequestUnavailableReason>> {
        if let Ok(cache) = self.github_viewer_login.lock()
            && let Some(login) = cache.clone()
        {
            return (Some(Ok(login)), None);
        }
        let (body, signal) = self.github_graphql_async("{ viewer { login } }").await;
        let Some(body) = body else {
            return (Some(Err(unavailable_reason_from_signal(signal))), signal);
        };
        let Ok(response) = serde_json::from_slice::<GqlViewerResponse>(&body) else {
            return (
                Some(Err(PullRequestUnavailableReason::GraphQlError)),
                signal,
            );
        };
        if response
            .errors
            .as_ref()
            .is_some_and(|errors| !errors.is_empty())
        {
            return (Some(Err(PullRequestUnavailableReason::Forbidden)), signal);
        }
        let Some(login) = response.data.map(|data| data.viewer.login) else {
            return (
                Some(Err(PullRequestUnavailableReason::GraphQlError)),
                signal,
            );
        };
        if let Ok(mut cache) = self.github_viewer_login.lock() {
            *cache = Some(login.clone());
        }
        (Some(Ok(login)), signal)
    }

    pub(crate) async fn fetch_open_pull_requests_async(
        &self,
        owner_repo: OwnerRepo,
    ) -> HttpOutcome<PullRequestFetch> {
        if !self.has_github_token() {
            return (
                Some(PullRequestFetch::Unavailable(
                    PullRequestUnavailableReason::Unauthenticated,
                )),
                None,
            );
        }
        if self
            .rate_limit()
            .graphql
            .is_some_and(|quota| quota.remaining == 0)
        {
            return (
                Some(PullRequestFetch::Unavailable(
                    PullRequestUnavailableReason::RateLimited,
                )),
                Some(ServiceSignal::RateLimited(ServiceKind::GitHub)),
            );
        }

        let (viewer, viewer_signal) = self.github_viewer_login_async().await;
        let Some(Ok(viewer_login)) = viewer else {
            let reason = viewer
                .and_then(Result::err)
                .unwrap_or_else(|| unavailable_reason_from_signal(viewer_signal));
            return (Some(PullRequestFetch::Unavailable(reason)), viewer_signal);
        };

        let search_query = format!(
            "repo:{}/{} is:pr is:open author:{viewer_login}",
            owner_repo.owner(),
            owner_repo.repo()
        );
        let (pages, signal) = self
            .fetch_pull_request_pages(&owner_repo, &search_query)
            .await;
        let Some(Ok((nodes, default_branch, completeness))) = pages else {
            let reason = pages
                .and_then(Result::err)
                .unwrap_or_else(|| unavailable_reason_from_signal(signal));
            return (Some(PullRequestFetch::Unavailable(reason)), signal);
        };
        let info = build_project_pr_info(
            owner_repo,
            viewer_login,
            default_branch,
            nodes,
            completeness,
        );
        (Some(PullRequestFetch::Loaded(info)), signal)
    }

    pub(crate) async fn fetch_pull_request_gone_reason_async(
        &self,
        owner_repo: OwnerRepo,
        number: u32,
    ) -> HttpOutcome<PullRequestGoneReason> {
        if !self.has_github_token() {
            return (Some(PullRequestGoneReason::Unknown), None);
        }
        let query = pull_request_status_query(owner_repo.owner(), owner_repo.repo(), number);
        let (body, signal) = self.github_graphql_async(&query).await;
        let Some(body) = body else {
            return (Some(PullRequestGoneReason::Unknown), signal);
        };
        let Ok(response) = serde_json::from_slice::<GqlPullRequestStatusResponse>(&body) else {
            return (Some(PullRequestGoneReason::Unknown), signal);
        };
        if response
            .errors
            .as_ref()
            .is_some_and(|errors| !errors.is_empty())
        {
            return (Some(PullRequestGoneReason::Unknown), signal);
        }
        let Some(repository) = response.data.and_then(|data| data.repository) else {
            return (Some(PullRequestGoneReason::Missing), signal);
        };
        let Some(pull_request) = repository.pull_request else {
            return (Some(PullRequestGoneReason::Missing), signal);
        };
        let reason = if pull_request.merged {
            PullRequestGoneReason::Merged {
                base: pull_request.base_ref_name,
            }
        } else if pull_request.closed {
            PullRequestGoneReason::Closed
        } else {
            PullRequestGoneReason::Unknown
        };
        (Some(reason), signal)
    }

    async fn fetch_pull_request_pages(
        &self,
        owner_repo: &OwnerRepo,
        search_query: &str,
    ) -> HttpOutcome<PullRequestPages> {
        let mut all_nodes = Vec::new();
        let mut cursor: Option<String> = None;
        let mut default_branch = None;
        let mut signal = None;

        for _ in 0..GITHUB_PR_PAGE_CAP {
            let query = pull_requests_query(
                owner_repo.owner(),
                owner_repo.repo(),
                search_query,
                cursor.as_deref(),
            );
            let (body, page_signal) = self.github_graphql_async(&query).await;
            signal = combine_optional_signal(signal, page_signal);
            let Some(body) = body else {
                return (Some(Err(unavailable_reason_from_signal(signal))), signal);
            };
            let Ok(response) = serde_json::from_slice::<GqlPullRequestsResponse>(&body) else {
                return (
                    Some(Err(PullRequestUnavailableReason::GraphQlError)),
                    signal,
                );
            };
            if response
                .errors
                .as_ref()
                .is_some_and(|errors| !errors.is_empty())
            {
                return (
                    Some(Err(PullRequestUnavailableReason::GraphQlError)),
                    signal,
                );
            }
            let Some(data) = response.data else {
                return (
                    Some(Err(PullRequestUnavailableReason::GraphQlError)),
                    signal,
                );
            };
            let Some(repository) = data.repository else {
                return (
                    Some(Err(PullRequestUnavailableReason::RepositoryMissing)),
                    signal,
                );
            };
            if default_branch.is_none() {
                default_branch = repository.default_branch_ref.map(|branch| branch.name);
            }
            let Some(search) = data.search else {
                return (
                    Some(Err(PullRequestUnavailableReason::GraphQlError)),
                    signal,
                );
            };
            all_nodes.extend(search.nodes.into_iter().flatten());
            if !search.page_info.has_next_page {
                return (
                    Some(Ok((
                        all_nodes,
                        default_branch.unwrap_or_else(|| "main".to_string()),
                        PullRequestCompleteness::Complete,
                    ))),
                    signal,
                );
            }
            let Some(next_cursor) = search.page_info.end_cursor else {
                return (
                    Some(Err(PullRequestUnavailableReason::IncompletePagination)),
                    signal,
                );
            };
            cursor = Some(next_cursor);
        }

        let shown = all_nodes.len();
        (
            Some(Ok((
                all_nodes,
                default_branch.unwrap_or_else(|| "main".to_string()),
                PullRequestCompleteness::Truncated { shown },
            ))),
            signal,
        )
    }

    /// Call GitHub's `/rate_limit` endpoint, which is itself exempt from
    /// the quota and therefore safe to poll while we're rate-limited.
    /// Updates the shared live `rate_limit` on success.
    pub(crate) async fn fetch_rate_limit_async(&self) -> HttpOutcome<GitHubRateLimit> {
        let Some(token) = self.github_auth.token() else {
            return (None, None);
        };
        let url = format!("{GITHUB_API_BASE}/rate_limit");
        let response = match self
            .client
            .get(&url)
            .header(AUTHORIZATION_HEADER, format!("Bearer {token}"))
            .header(ACCEPT_HEADER, GITHUB_JSON_MEDIA_TYPE)
            .send()
            .await
        {
            Ok(response) => response,
            Err(error) => return (None, classify_network_error(ServiceKind::GitHub, &error)),
        };
        let body = match response.bytes().await {
            Ok(body) => body,
            Err(error) => {
                return (
                    None,
                    classify_network_error(ServiceKind::GitHub, &error)
                        .or(Some(ServiceSignal::Reachable(ServiceKind::GitHub))),
                );
            },
        };
        let Ok(json) = serde_json::from_slice::<serde_json::Value>(&body) else {
            return (None, Some(ServiceSignal::Reachable(ServiceKind::GitHub)));
        };
        let github_rate_limit = parse_rate_limit_response(&json);
        self.set_rate_limit(github_rate_limit);
        (
            Some(github_rate_limit),
            Some(ServiceSignal::Reachable(ServiceKind::GitHub)),
        )
    }

    /// Recovery probe used while retrying after an `Unreachable` signal.
    ///
    /// For GitHub, a plain `HEAD https://api.github.com` is not enough —
    /// it returns 200 even when fully rate-limited (no auth, no quota
    /// debit). That made "recovery" fire within ~100ms of every
    /// Unreachable signal, dismissing the toast only to have it
    /// immediately re-created by the next 429. Use `/rate_limit` (which
    /// is exempt from the quota) and treat the service as recovered
    /// only when both core and graphql have at least 1 request
    /// remaining. While the debug force flag is on, GitHub never
    /// recovers — the probe always returns `false`.
    pub(crate) async fn probe_service_async(&self, service: ServiceKind) -> bool {
        match service {
            ServiceKind::GitHub => self.probe_github_rate_limit_async().await,
            ServiceKind::CratesIo => self
                .client
                .head(service.probe_url())
                .timeout(Duration::from_secs(SERVICE_RETRY_SECS))
                .send()
                .await
                .is_ok(),
        }
    }

    async fn probe_github_rate_limit_async(&self) -> bool {
        let (github_rate_limit, _signal) = self.fetch_rate_limit_async().await;
        if self.github_rate_limit_forced() {
            // Forced mode: display keeps updating via /rate_limit above,
            // but never report recovery — the error toast must persist
            // for testing.
            return false;
        }
        match github_rate_limit {
            Some(s) => {
                s.core.is_some_and(|q| q.remaining > 0)
                    && s.graphql.is_some_and(|q| q.remaining > 0)
            },
            None => self
                .client
                .head(ServiceKind::GitHub.probe_url())
                .timeout(Duration::from_secs(SERVICE_RETRY_SECS))
                .send()
                .await
                .is_ok(),
        }
    }

    /// Fetch version and download count from the crates.io API (async).
    pub(crate) async fn fetch_crates_io_info_async(
        &self,
        crate_name: &str,
    ) -> HttpOutcome<CratesIoInfo> {
        let url = format!("{CRATES_IO_API_BASE}/crates/{crate_name}");
        let response = match self
            .client
            .get(&url)
            .header(USER_AGENT_HEADER, CRATES_IO_USER_AGENT)
            .send()
            .await
        {
            Ok(response) => response,
            Err(error) => return (None, classify_network_error(ServiceKind::CratesIo, &error)),
        };
        // Surface a 429 as a rate-limit signal instead of a silent miss:
        // the service state machine pauses, probes, and refetches the
        // missing versions on recovery. Without this the body parse below
        // yields no version while reporting the service reachable.
        if response.status() == reqwest::StatusCode::TOO_MANY_REQUESTS {
            return (
                None,
                Some(ServiceSignal::RateLimited(ServiceKind::CratesIo)),
            );
        }
        let body = match response.bytes().await {
            Ok(body) => body,
            Err(error) => {
                return (
                    None,
                    classify_network_error(ServiceKind::CratesIo, &error)
                        .or(Some(ServiceSignal::Reachable(ServiceKind::CratesIo))),
                );
            },
        };
        let Ok(json) = serde_json::from_slice::<serde_json::Value>(&body) else {
            return (None, Some(ServiceSignal::Reachable(ServiceKind::CratesIo)));
        };
        let Some(krate) = json.get(CRATES_IO_CRATE_KEY) else {
            return (None, Some(ServiceSignal::Reachable(ServiceKind::CratesIo)));
        };
        (
            crates_io_info_from_crate(krate),
            Some(ServiceSignal::Reachable(ServiceKind::CratesIo)),
        )
    }

    // ── Sync wrappers (for std/rayon thread callers) ────────────────

    /// List recent completed workflow runs (sync wrapper).
    pub(crate) fn list_runs(
        &self,
        owner: &str,
        repo: &str,
        branch: Option<&str>,
        count: u32,
        created_before: Option<&str>,
    ) -> HttpOutcome<GhRunsList> {
        self.handle
            .block_on(self.list_runs_async(owner, repo, branch, count, created_before))
    }

    /// Batch-fetch job details + repo metadata (sync wrapper).
    pub(crate) fn batch_fetch_jobs_and_meta(
        &self,
        owner: &str,
        repo: &str,
        runs: &[&GhRun],
    ) -> HttpOutcome<GitHubJobsAndMeta> {
        self.handle
            .block_on(self.batch_fetch_jobs_and_meta_async(owner, repo, runs))
    }

    pub(crate) fn fetch_open_pull_requests(
        &self,
        owner_repo: OwnerRepo,
    ) -> HttpOutcome<PullRequestFetch> {
        self.handle
            .block_on(self.fetch_open_pull_requests_async(owner_repo))
    }

    pub(crate) fn fetch_pull_request_gone_reason(
        &self,
        owner_repo: OwnerRepo,
        number: u32,
    ) -> HttpOutcome<PullRequestGoneReason> {
        self.handle
            .block_on(self.fetch_pull_request_gone_reason_async(owner_repo, number))
    }

    pub(crate) fn probe_service(&self, service: ServiceKind) -> bool {
        self.handle.block_on(self.probe_service_async(service))
    }

    /// Fetch `/rate_limit` (sync wrapper).
    pub(crate) fn fetch_rate_limit(&self) -> HttpOutcome<GitHubRateLimit> {
        self.handle.block_on(self.fetch_rate_limit_async())
    }

    /// Fetch crates.io info (sync wrapper).
    pub(crate) fn fetch_crates_io_info(&self, crate_name: &str) -> HttpOutcome<CratesIoInfo> {
        self.handle
            .block_on(self.fetch_crates_io_info_async(crate_name))
    }
}

fn build_client() -> Result<Client, Error> {
    reqwest::Client::builder()
        .timeout(GH_TIMEOUT)
        .user_agent(APP_NAME)
        .build()
}

/// Select the version to show and (when distinct) the newer prerelease
/// from a crates.io `crate` object. `max_stable_version` is the latest
/// stable; `max_version` is the highest non-yanked release including
/// prereleases, so when it differs from the stable it must be a newer
/// prerelease. A crate with only prereleases shows the newest as its
/// version. Returns `None` when neither field is present.
fn crates_io_info_from_crate(krate: &Value) -> Option<CratesIoInfo> {
    let stable = krate
        .get(CRATES_IO_MAX_STABLE_VERSION_KEY)
        .and_then(serde_json::Value::as_str);
    let newest = krate
        .get(CRATES_IO_MAX_VERSION_KEY)
        .and_then(serde_json::Value::as_str);
    let (version, prerelease) = match (stable, newest) {
        (Some(stable), Some(newest)) if newest != stable && newest.contains('-') => {
            (stable.to_string(), Some(newest.to_string()))
        },
        (Some(stable), _) => (stable.to_string(), None),
        (None, Some(newest)) => (newest.to_string(), None),
        (None, None) => return None,
    };
    let downloads = krate
        .get(CRATES_IO_DOWNLOADS_KEY)
        .and_then(serde_json::Value::as_u64)
        .unwrap_or(0);
    Some(CratesIoInfo {
        version,
        prerelease,
        downloads,
    })
}

#[cfg(test)]
#[allow(
    clippy::expect_used,
    reason = "tests should panic on unexpected values"
)]
mod crates_io_tests {
    use super::crates_io_info_from_crate;

    #[test]
    fn stable_with_newer_prerelease_returns_both() {
        let krate = serde_json::json!({
            "max_stable_version": "0.20.2",
            "max_version": "0.21.0-rc.2",
            "downloads": 663,
        });
        let info = crates_io_info_from_crate(&krate).expect("info");
        assert_eq!(info.version, "0.20.2");
        assert_eq!(info.prerelease.as_deref(), Some("0.21.0-rc.2"));
        assert_eq!(info.downloads, 663);
    }

    #[test]
    fn stable_without_newer_prerelease_omits_prerelease() {
        let krate = serde_json::json!({
            "max_stable_version": "1.2.3",
            "max_version": "1.2.3",
            "downloads": 10,
        });
        let info = crates_io_info_from_crate(&krate).expect("info");
        assert_eq!(info.version, "1.2.3");
        assert_eq!(info.prerelease, None);
    }

    #[test]
    fn only_prereleases_shows_newest_as_version() {
        let krate = serde_json::json!({
            "max_stable_version": serde_json::Value::Null,
            "max_version": "0.1.0-alpha.1",
            "downloads": 5,
        });
        let info = crates_io_info_from_crate(&krate).expect("info");
        assert_eq!(info.version, "0.1.0-alpha.1");
        assert_eq!(info.prerelease, None);
    }

    #[test]
    fn no_versions_returns_none() {
        let krate = serde_json::json!({ "downloads": 0 });
        assert!(crates_io_info_from_crate(&krate).is_none());
    }
}

#[cfg(test)]
#[allow(
    clippy::expect_used,
    reason = "tests should panic on unexpected values"
)]
#[allow(
    clippy::unwrap_used,
    reason = "tests should panic on unexpected values"
)]
mod tests {
    use std::io::Read;
    use std::io::Write as _;
    use std::net::TcpListener;
    use std::thread;

    use reqwest::StatusCode;
    use reqwest::header::HeaderMap;
    use serde_json::json;
    use tokio::runtime::Handle;

    use super::*;
    use crate::test_support;

    /// Exercises `GithubAuth::classify` directly with constructed process
    /// outcomes — the one place the missing-vs-logged-out distinction is
    /// decided. Gated to unix because `ExitStatus` is only constructible
    /// there (`ExitStatusExt::from_raw`); the primary platforms are unix.
    #[cfg(unix)]
    mod classify {
        use std::io;
        use std::io::ErrorKind;
        use std::os::unix::process::ExitStatusExt;
        use std::process::ExitStatus;
        use std::process::Output;

        use super::GithubAuth;

        fn gh_output(raw_wait_status: i32, stdout: &[u8]) -> Output {
            Output {
                status: ExitStatus::from_raw(raw_wait_status),
                stdout: stdout.to_vec(),
                stderr: Vec::new(),
            }
        }

        #[test]
        fn success_exit_with_token_is_authenticated() {
            // raw wait status 0 encodes a normal exit with code 0 (success).
            let github_auth = GithubAuth::classify(Ok(gh_output(0, b"  gho_abc123\n")));
            assert!(
                matches!(github_auth, GithubAuth::Authenticated(token) if token == "gho_abc123")
            );
        }

        #[test]
        fn success_exit_with_invalid_utf8_is_unauthenticated() {
            let github_auth = GithubAuth::classify(Ok(gh_output(0, &[0xff, 0xfe])));
            assert!(matches!(github_auth, GithubAuth::Unauthenticated));
        }

        #[test]
        fn nonsuccess_exit_is_unauthenticated() {
            // raw wait status `1 << 8` encodes a normal exit with code 1.
            let github_auth = GithubAuth::classify(Ok(gh_output(1 << 8, b"not logged in")));
            assert!(matches!(github_auth, GithubAuth::Unauthenticated));
        }

        #[test]
        fn missing_binary_is_not_installed() {
            let github_auth = GithubAuth::classify(Err(io::Error::from(ErrorKind::NotFound)));
            assert!(matches!(github_auth, GithubAuth::NotInstalled));
        }

        #[test]
        fn other_spawn_error_is_unauthenticated() {
            let github_auth =
                GithubAuth::classify(Err(io::Error::from(ErrorKind::PermissionDenied)));
            assert!(matches!(github_auth, GithubAuth::Unauthenticated));
        }
    }

    #[test]
    fn rate_limit_headers_core_bucket_parsed() {
        let headers = test_support::header_map(&[
            ("x-ratelimit-resource", "core"),
            ("x-ratelimit-limit", "5000"),
            ("x-ratelimit-used", "42"),
            ("x-ratelimit-remaining", "4958"),
            ("x-ratelimit-reset", "1717000000"),
        ]);
        let (bucket, quota) = parse_rate_limit_headers(&headers).unwrap();
        assert_eq!(bucket, RateLimitBucket::Core);
        assert_eq!(quota.limit, 5000);
        assert_eq!(quota.used, 42);
        assert_eq!(quota.remaining, 4958);
        assert_eq!(quota.reset_at, Some(1_717_000_000));
    }

    #[test]
    fn rate_limit_headers_graphql_bucket_parsed() {
        let headers = test_support::header_map(&[
            ("x-ratelimit-resource", "graphql"),
            ("x-ratelimit-limit", "5000"),
            ("x-ratelimit-used", "12"),
            ("x-ratelimit-remaining", "4988"),
            ("x-ratelimit-reset", "1717000000"),
        ]);
        let (bucket, _) = parse_rate_limit_headers(&headers).unwrap();
        assert_eq!(bucket, RateLimitBucket::GraphQl);
    }

    #[test]
    fn rate_limit_headers_missing_are_none() {
        let headers = test_support::header_map(&[("x-ratelimit-resource", "core")]);
        assert!(parse_rate_limit_headers(&headers).is_none());
    }

    #[test]
    fn rate_limit_headers_unknown_bucket_is_none() {
        let headers = test_support::header_map(&[
            ("x-ratelimit-resource", "search"),
            ("x-ratelimit-limit", "30"),
            ("x-ratelimit-used", "0"),
            ("x-ratelimit-remaining", "30"),
        ]);
        assert!(parse_rate_limit_headers(&headers).is_none());
    }

    #[test]
    fn parse_rate_limit_response_parses_both_buckets() {
        let body = json!({
            "resources": {
                "core":    { "limit": 5000, "used": 42,  "remaining": 4958, "reset": 1_717_000_000 },
                "graphql": { "limit": 5000, "used": 12,  "remaining": 4988, "reset": 1_717_000_000 },
            },
        });
        let github_rate_limit = parse_rate_limit_response(&body);
        let core = github_rate_limit.core.unwrap();
        assert_eq!(core.limit, 5000);
        assert_eq!(core.used, 42);
        assert_eq!(core.remaining, 4958);
        assert_eq!(core.reset_at, Some(1_717_000_000));
        let gql = github_rate_limit.graphql.unwrap();
        assert_eq!(gql.limit, 5000);
        assert_eq!(gql.remaining, 4988);
    }

    #[test]
    fn parse_rate_limit_response_missing_bucket_is_none() {
        let body = json!({
            "resources": {
                "core": { "limit": 5000, "used": 0, "remaining": 5000 },
            },
        });
        let github_rate_limit = parse_rate_limit_response(&body);
        assert!(github_rate_limit.core.is_some());
        assert!(github_rate_limit.graphql.is_none());
    }

    #[test]
    fn github_is_rate_limited_on_429() {
        let headers = HeaderMap::new();
        assert!(github_is_rate_limited(
            StatusCode::TOO_MANY_REQUESTS,
            &headers
        ));
    }

    #[test]
    fn github_is_rate_limited_on_403_with_zero_remaining() {
        let headers = test_support::header_map(&[("x-ratelimit-remaining", "0")]);
        assert!(github_is_rate_limited(StatusCode::FORBIDDEN, &headers));
    }

    #[test]
    fn github_is_not_rate_limited_on_403_with_remaining() {
        let headers = test_support::header_map(&[("x-ratelimit-remaining", "500")]);
        assert!(!github_is_rate_limited(StatusCode::FORBIDDEN, &headers));
    }

    #[test]
    fn github_is_not_rate_limited_on_200() {
        let headers = test_support::header_map(&[("x-ratelimit-remaining", "0")]);
        assert!(!github_is_rate_limited(StatusCode::OK, &headers));
    }

    #[test]
    fn graphql_rate_limited_body_is_detected() {
        let body = json!({ "errors": [{ "type": "RATE_LIMITED", "message": "x" }] });
        assert!(graphql_body_is_rate_limited(&body));
    }

    #[test]
    fn graphql_body_without_errors_is_not_rate_limited() {
        let body = json!({ "data": { "repo": null } });
        assert!(!graphql_body_is_rate_limited(&body));
    }

    #[test]
    fn graphql_body_with_unrelated_errors_is_not_rate_limited() {
        let body = json!({ "errors": [{ "type": "NOT_FOUND", "message": "x" }] });
        assert!(!graphql_body_is_rate_limited(&body));
    }

    fn test_client(handle: &Handle) -> HttpClient {
        HttpClient {
            client:                  build_client().expect("build http client"),
            github_auth:             GithubAuth::Unauthenticated,
            github_viewer_login:     Arc::new(Mutex::new(None)),
            rate_limit:              Arc::new(Mutex::new(GitHubRateLimit::default())),
            force_github_rate_limit: Arc::new(AtomicBool::new(false)),
            force_reset_at:          Arc::new(AtomicU64::new(0)),
            handle:                  handle.clone(),
        }
    }

    #[test]
    fn force_rate_limit_synthesizes_zero_core_with_future_reset() {
        let runtime = test_support::test_runtime();
        let client = test_client(runtime.handle());
        let real_graphql = RateLimitQuota {
            limit:     5000,
            used:      12,
            remaining: 4988,
            reset_at:  Some(1_800_000_000),
        };
        client.update_rate_limit_bucket(RateLimitBucket::GraphQl, real_graphql);

        let before = now_epoch_secs();
        client.set_force_github_rate_limit(true);
        let after = now_epoch_secs();

        let github_rate_limit = client.rate_limit();
        let core = github_rate_limit.core.expect("synthetic core bucket");
        assert_eq!(core.limit, 5000);
        assert_eq!(core.remaining, 0);
        assert_eq!(core.used, 5000);
        let reset_at = core.reset_at.expect("synthetic reset_at");
        assert!(reset_at >= before + SYNTHETIC_RATE_LIMIT_SECS);
        assert!(reset_at <= after + SYNTHETIC_RATE_LIMIT_SECS);

        // `graphql` stays real so the live-refresh path is still
        // observable during debug.
        assert_eq!(github_rate_limit.graphql, Some(real_graphql));

        client.set_force_github_rate_limit(false);
        let github_rate_limit = client.rate_limit();
        // Real core was never populated, so clearing force leaves it
        // at `None`.
        assert!(github_rate_limit.core.is_none());
        assert_eq!(github_rate_limit.graphql, Some(real_graphql));
    }

    #[test]
    fn rate_limit_reflects_bucket_updates() {
        let runtime = test_support::test_runtime();
        let client = test_client(runtime.handle());

        assert_eq!(client.rate_limit(), GitHubRateLimit::default());

        let core_quota = RateLimitQuota {
            limit:     5000,
            used:      42,
            remaining: 4958,
            reset_at:  Some(1_717_000_000),
        };
        client.update_rate_limit_bucket(RateLimitBucket::Core, core_quota);
        let github_rate_limit = client.rate_limit();
        assert_eq!(github_rate_limit.core, Some(core_quota));
        assert!(github_rate_limit.graphql.is_none());

        let gql_quota = RateLimitQuota {
            limit:     5000,
            used:      1,
            remaining: 4999,
            reset_at:  None,
        };
        client.update_rate_limit_bucket(RateLimitBucket::GraphQl, gql_quota);
        let github_rate_limit = client.rate_limit();
        assert_eq!(github_rate_limit.core, Some(core_quota));
        assert_eq!(github_rate_limit.graphql, Some(gql_quota));
    }

    #[test]
    fn client_sends_app_user_agent_header() {
        let listener = TcpListener::bind("127.0.0.1:0").expect("bind test listener");
        let addr = listener.local_addr().expect("read listener address");
        let server = thread::spawn(move || {
            let (mut stream, _) = listener.accept().expect("accept request");
            let mut buffer = [0_u8; 4096];
            let size = stream.read(&mut buffer).expect("read request bytes");
            let request = String::from_utf8_lossy(&buffer[..size]).into_owned();
            let response = b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\nConnection: close\r\n\r\nOK";
            stream.write_all(response).expect("write response");
            request
        });

        let runtime = test_support::test_runtime();
        let client = build_client().expect("build http client");
        let url = format!("http://{addr}/");
        let response = runtime
            .block_on(async { client.get(url).send().await })
            .expect("send request");
        assert!(response.status().is_success());

        let request = server.join().expect("join server thread");
        assert!(
            request.contains(&format!("user-agent: {APP_NAME}\r\n"))
                || request.contains(&format!("User-Agent: {APP_NAME}\r\n")),
            "expected request to include User-Agent header, got:\n{request}"
        );
    }
}