thirtyfour 0.37.8

Thirtyfour is a Selenium / WebDriver library for Rust, for automated website UI testing. Tested on Chrome and Firefox, but any webdriver-capable browser should work.
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
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::{Duration, Instant};

use fs4::tokio::AsyncFileExt;
use serde::Deserialize;
use url::Url;

use super::browser::{BrowserKind, major};
use super::error::ManagerError;
use super::status::{Emitter, Status, VersionSource};
use super::version::DriverVersion;

/// Built-in upstream metadata sources.
///
/// The chromedriver download URL comes fully-qualified from the
/// Chrome-for-Testing JSON index, so there's no separate base-URL field for
/// it. Geckodriver metadata is only needed for [`DriverVersion::Latest`];
/// other geckodriver versions come from the embedded compatibility table.
#[derive(Debug, Clone)]
pub(crate) struct Mirror {
    /// Base URL for the Chrome-for-Testing JSON metadata. Defaults to the
    /// public CfT endpoint.
    pub chrome_metadata: Url,
    /// Base URL for geckodriver release pages: `<base>latest` must redirect
    /// to `<base>tag/v<version>`. Defaults to
    /// `github.com/mozilla/geckodriver/releases/`.
    pub geckodriver_metadata: Url,
    /// Base URL for geckodriver binary downloads. Defaults to the public
    /// `github.com/mozilla/geckodriver/releases/download/` host.
    pub geckodriver_downloads: Url,
    /// Base URL for the msedgedriver download host.
    pub edge_downloads: Url,
}

impl Default for Mirror {
    fn default() -> Self {
        Self {
            chrome_metadata: Url::parse("https://googlechromelabs.github.io/").unwrap(),
            geckodriver_metadata: Url::parse("https://github.com/mozilla/geckodriver/releases/")
                .unwrap(),
            geckodriver_downloads: Url::parse(
                "https://github.com/mozilla/geckodriver/releases/download/",
            )
            .unwrap(),
            edge_downloads: Url::parse("https://msedgedriver.microsoft.com/").unwrap(),
        }
    }
}

/// Configuration values consumed by the download / cache logic.
pub(crate) struct DownloadConfig {
    pub cache_dir: PathBuf,
    pub mirror: Mirror,
    pub download_timeout: Duration,
    pub offline: bool,
}

/// Resolve [`DriverVersion`] to a concrete version string.
///
/// `local_version` must be supplied when the variant is `MatchLocalBrowser`;
/// `caps_version` when the variant is `FromCapabilities`. For system-managed
/// browsers (Safari) the version resolution is skipped entirely — the caller
/// is expected to short-circuit before calling this function.
///
/// For Firefox, `MatchLocalBrowser` and `FromCapabilities` apply the
/// geckodriver→Firefox compatibility table from [`geckodriver_for_firefox`]:
/// modern Firefox (≥115) gets latest geckodriver; older Firefox installs are
/// mapped to a pinned older geckodriver tag.
pub(crate) async fn resolve_version(
    client: &reqwest::Client,
    cfg: &DownloadConfig,
    browser: BrowserKind,
    spec: &DriverVersion,
    local_version: Option<&str>,
    caps_version: Option<&str>,
    emitter: &Emitter,
) -> Result<String, ManagerError> {
    if browser == BrowserKind::Safari {
        return Ok("system".to_string());
    }

    emitter.emit(Status::DriverVersionResolving {
        browser,
        requested: spec.clone(),
    });

    let resolve_firefox_for_browser_version = |fx: &str| -> Result<String, ManagerError> {
        geckodriver_for_firefox(fx).map(str::to_owned).ok_or_else(|| {
            ManagerError::Parse(format!(
                "no geckodriver release in compatibility table covers Firefox {fx}"
            ))
        })
    };

    let resolved = match spec {
        DriverVersion::Exact(v) => match browser {
            BrowserKind::Chrome => resolve_chrome_exact(client, cfg, v).await?,
            BrowserKind::Firefox => resolve_firefox_exact(client, cfg, v).await?,
            BrowserKind::Edge => resolve_edge_exact(client, cfg, v).await?,
            BrowserKind::Safari => unreachable!("safari short-circuited above"),
        },
        DriverVersion::Latest => match browser {
            // Offline, the newest driver in the cache stands in for the latest.
            BrowserKind::Chrome | BrowserKind::Edge | BrowserKind::Firefox if cfg.offline => {
                newest_cached(cfg, browser, None)?
            }
            BrowserKind::Chrome => fetch_chrome_latest(client, cfg).await?,
            BrowserKind::Firefox => fetch_firefox_latest(client, cfg).await?,
            BrowserKind::Edge => fetch_edge_latest(client, cfg).await?,
            BrowserKind::Safari => unreachable!("safari short-circuited above"),
        },
        DriverVersion::MatchLocalBrowser => {
            let v = local_version.ok_or(ManagerError::LocalBrowserNotFound {
                browser: browser.display_name(),
                hint: "local version probe returned no value",
            })?;
            match browser {
                BrowserKind::Chrome => resolve_chrome_exact(client, cfg, v).await?,
                BrowserKind::Edge => resolve_edge_exact(client, cfg, v).await?,
                BrowserKind::Firefox => resolve_firefox_for_browser_version(v)?,
                BrowserKind::Safari => unreachable!("safari short-circuited above"),
            }
        }
        DriverVersion::FromCapabilities => {
            let v = caps_version.ok_or(ManagerError::MissingCapabilityVersion)?;
            match browser {
                BrowserKind::Chrome => resolve_chrome_exact(client, cfg, v).await?,
                BrowserKind::Edge => resolve_edge_exact(client, cfg, v).await?,
                BrowserKind::Firefox => resolve_firefox_for_browser_version(v)?,
                BrowserKind::Safari => unreachable!("safari short-circuited above"),
            }
        }
    };

    emitter.emit(Status::DriverVersionResolved {
        browser,
        version: resolved.clone(),
        source: VersionSource::from_spec(spec),
    });
    Ok(resolved)
}

/// One entry in the geckodriver↔Firefox compatibility table.
struct GeckodriverRelease {
    /// Tag without the leading `v` (e.g. `"0.36.0"`).
    version: &'static str,
    /// Minimum Firefox major version supported by this geckodriver.
    min_firefox: u32,
    /// Maximum Firefox major version, if this geckodriver was superseded.
    /// `None` means "still supported" — typical for the entries at the top
    /// of the table.
    max_firefox: Option<u32>,
}

/// Embedded geckodriver compatibility table, **sorted descending by
/// geckodriver version** (highest first).
///
/// Modelled after [SeleniumHQ's `geckodriver-support.json`][upstream] but
/// embedded here so we don't hit any network endpoint to resolve a Firefox →
/// geckodriver mapping. Update when a new geckodriver release ships (roughly
/// every 6–12 months); the manager-tests CI workflow will catch staleness if
/// upstream introduces a Firefox version that no entry covers.
///
/// [upstream]: https://github.com/SeleniumHQ/selenium/blob/trunk/common/geckodriver/geckodriver-support.json
const GECKODRIVER_RELEASES: &[GeckodriverRelease] = &[
    GeckodriverRelease {
        version: "0.36.0",
        min_firefox: 128,
        max_firefox: None,
    },
    GeckodriverRelease {
        version: "0.35.0",
        min_firefox: 115,
        max_firefox: None,
    },
    GeckodriverRelease {
        version: "0.34.0",
        min_firefox: 115,
        max_firefox: None,
    },
    GeckodriverRelease {
        version: "0.33.0",
        min_firefox: 102,
        max_firefox: Some(120),
    },
    GeckodriverRelease {
        version: "0.32.2",
        min_firefox: 102,
        max_firefox: Some(120),
    },
    GeckodriverRelease {
        version: "0.31.0",
        min_firefox: 91,
        max_firefox: Some(120),
    },
    GeckodriverRelease {
        version: "0.30.0",
        min_firefox: 78,
        max_firefox: Some(90),
    },
    GeckodriverRelease {
        version: "0.29.1",
        min_firefox: 60,
        max_firefox: Some(90),
    },
];

/// Pick the best geckodriver release for the given Firefox version. Returns
/// the highest-versioned entry whose `[min_firefox, max_firefox]` range
/// covers `firefox_version`. Returns `None` when no entry matches (e.g.
/// Firefox is older than anything in the table).
fn geckodriver_for_firefox(firefox_version: &str) -> Option<&'static str> {
    let major: u32 = firefox_version.split('.').next().and_then(|s| s.parse().ok()).unwrap_or(0);
    GECKODRIVER_RELEASES
        .iter()
        .find(|r| major >= r.min_firefox && r.max_firefox.is_none_or(|max| major <= max))
        .map(|r| r.version)
}

#[derive(Deserialize)]
struct ChromeKnownGoodVersions {
    versions: Vec<ChromeVersionEntry>,
}

#[derive(Deserialize)]
struct ChromeVersionEntry {
    version: String,
    downloads: ChromeDownloads,
}

#[derive(Deserialize)]
struct ChromeDownloads {
    #[serde(default)]
    chromedriver: Vec<ChromePlatformDownload>,
}

#[derive(Deserialize, Clone)]
struct ChromePlatformDownload {
    platform: String,
    url: String,
}

async fn fetch_chrome_index(
    client: &reqwest::Client,
    cfg: &DownloadConfig,
) -> Result<ChromeKnownGoodVersions, ManagerError> {
    let url = cfg
        .mirror
        .chrome_metadata
        .join("chrome-for-testing/known-good-versions-with-downloads.json")
        .map_err(|e| ManagerError::Parse(e.to_string()))?;
    let resp = client.get(url).timeout(cfg.download_timeout).send().await?.error_for_status()?;
    let body: ChromeKnownGoodVersions = resp.json().await?;
    Ok(body)
}

async fn fetch_chrome_latest(
    client: &reqwest::Client,
    cfg: &DownloadConfig,
) -> Result<String, ManagerError> {
    let url = cfg
        .mirror
        .chrome_metadata
        .join("chrome-for-testing/LATEST_RELEASE_STABLE")
        .map_err(|e| ManagerError::Parse(e.to_string()))?;
    let resp = client.get(url).timeout(cfg.download_timeout).send().await?.error_for_status()?;
    Ok(resp.text().await?.trim().to_string())
}

async fn resolve_chrome_exact(
    client: &reqwest::Client,
    cfg: &DownloadConfig,
    version: &str,
) -> Result<String, ManagerError> {
    // A full version already in the cache was downloaded from the index, so
    // fetching the index again would only confirm it.
    if version.contains('.') && cached_driver_path(cfg, BrowserKind::Chrome, version).exists() {
        return Ok(version.to_string());
    }
    // Without the index, the closest is the newest cached driver of the major.
    if cfg.offline {
        return newest_cached(cfg, BrowserKind::Chrome, Some(major(version)));
    }
    let index = fetch_chrome_index(client, cfg).await?;
    if version.contains('.') {
        // Try exact match; fall back to latest matching the same major if the
        // exact build isn't present in CfT (common for older Chrome installs).
        if index.versions.iter().any(|v| v.version == version) {
            return Ok(version.to_string());
        }
    }
    let m = major(version);
    let mut matches: Vec<&ChromeVersionEntry> =
        index.versions.iter().filter(|v| major(&v.version) == m).collect();
    matches.sort_by(|a, b| sort_semver(&a.version, &b.version));
    matches
        .last()
        .map(|v| v.version.clone())
        .ok_or_else(|| ManagerError::Parse(format!("no chromedriver release for major {m}")))
}

fn sort_semver(a: &str, b: &str) -> std::cmp::Ordering {
    let parse =
        |s: &str| -> Vec<u32> { s.split('.').map(|p| p.parse::<u32>().unwrap_or(0)).collect() };
    parse(a).cmp(&parse(b))
}

/// `DriverVersion::Latest` for Firefox: the newest geckodriver release.
///
/// Read from where `releases/latest` redirects (`releases/tag/v0.36.0`)
/// rather than the GitHub REST API, which allows only 60 unauthenticated
/// requests an hour, and `latest()` resolves on every launch.
async fn fetch_firefox_latest(
    client: &reqwest::Client,
    cfg: &DownloadConfig,
) -> Result<String, ManagerError> {
    let url = cfg
        .mirror
        .geckodriver_metadata
        .join("latest")
        .map_err(|e| ManagerError::Parse(e.to_string()))?;
    let resp = client.head(url).timeout(cfg.download_timeout).send().await?.error_for_status()?;
    let release = resp.url();
    release
        .path_segments()
        .and_then(|mut segments| segments.next_back())
        .and_then(|tag| tag.strip_prefix('v'))
        .filter(|v| v.split('.').all(|p| p.parse::<u32>().is_ok()))
        .map(str::to_owned)
        .ok_or_else(|| {
            ManagerError::Parse(format!("unexpected geckodriver latest-release URL: {release}"))
        })
}

async fn fetch_edge_latest(
    client: &reqwest::Client,
    cfg: &DownloadConfig,
) -> Result<String, ManagerError> {
    let url = cfg
        .mirror
        .edge_downloads
        .join("LATEST_STABLE")
        .map_err(|e| ManagerError::Parse(e.to_string()))?;
    let bytes = client
        .get(url)
        .timeout(cfg.download_timeout)
        .send()
        .await?
        .error_for_status()?
        .bytes()
        .await?;
    Ok(decode_edge_text(&bytes).trim().to_string())
}

async fn resolve_edge_exact(
    client: &reqwest::Client,
    cfg: &DownloadConfig,
    version: &str,
) -> Result<String, ManagerError> {
    if version.contains('.') {
        return Ok(version.to_string());
    }
    if cfg.offline {
        return newest_cached(cfg, BrowserKind::Edge, Some(major(version)));
    }
    // Major-only request: msedgedriver doesn't expose an index; fetch
    // `LATEST_RELEASE_<major>` from the same host.
    let url = cfg
        .mirror
        .edge_downloads
        .join(&format!("LATEST_RELEASE_{version}"))
        .map_err(|e| ManagerError::Parse(e.to_string()))?;
    let resp = client.get(url).timeout(cfg.download_timeout).send().await?;
    if !resp.status().is_success() {
        // Fall back to latest stable rather than error — best-effort resolution.
        return fetch_edge_latest(client, cfg).await;
    }
    let bytes = resp.bytes().await?;
    Ok(decode_edge_text(&bytes).trim().to_string())
}

/// The msedgedriver `LATEST_*` endpoints return text encoded as UTF-16 LE with
/// a BOM (older endpoint behavior preserved by Microsoft). Decode that, falling
/// back to UTF-8 if no BOM is present.
fn decode_edge_text(bytes: &[u8]) -> String {
    if bytes.len() >= 2 && bytes[0] == 0xFF && bytes[1] == 0xFE {
        let utf16: Vec<u16> =
            bytes[2..].chunks_exact(2).map(|c| u16::from_le_bytes([c[0], c[1]])).collect();
        String::from_utf16_lossy(&utf16)
    } else {
        String::from_utf8_lossy(bytes).into_owned()
    }
}

async fn resolve_firefox_exact(
    _client: &reqwest::Client,
    _cfg: &DownloadConfig,
    version: &str,
) -> Result<String, ManagerError> {
    // `DriverVersion::Exact(...)` for Firefox is a literal geckodriver tag
    // (e.g. "0.36.0"). We don't probe upstream to verify it exists — if the
    // user supplies a wrong tag, the download itself will 404 with a clear
    // error message. Probing would just double the network calls and the
    // failure modes.
    Ok(version.trim_start_matches('v').to_string())
}

/// Where a downloaded driver binary lives in the cache.
pub(crate) struct DriverPath {
    pub binary: PathBuf,
}

/// Ensure the driver for `(browser, version)` is present in the cache; download
/// it if not. Returns the path to the executable.
///
/// For system-managed browsers (Safari) this returns the path to the
/// pre-installed system driver and skips download / cache entirely.
pub(crate) async fn ensure_driver(
    client: &reqwest::Client,
    cfg: &DownloadConfig,
    browser: BrowserKind,
    version: &str,
    emitter: &Emitter,
) -> Result<DriverPath, ManagerError> {
    if browser == BrowserKind::Safari {
        return safari_driver_path();
    }

    let dir = cached_driver_dir(cfg, browser, version);
    let bin_path = dir.join(exe_name(browser));

    if bin_path.exists() {
        emitter.emit(Status::DriverCacheHit {
            browser,
            version: version.to_string(),
            path: bin_path.clone(),
        });
        return Ok(DriverPath {
            binary: bin_path,
        });
    }

    if cfg.offline {
        return Err(ManagerError::Offline);
    }

    tokio::fs::create_dir_all(&dir).await?;
    let lock_path = cfg.cache_dir.join(format!("{}-{}.lock", browser.cache_dir_name(), version));
    if let Some(parent) = lock_path.parent() {
        tokio::fs::create_dir_all(parent).await?;
    }

    // Hold an OS-level exclusive lock on the lock file while we
    // download+extract, so concurrent test processes don't race the same cache
    // entry. The lock is released when `lock_file` drops at end of scope.
    //
    // `AsyncFileExt::lock` is sync under the hood (it calls flock /
    // LockFileEx) — it briefly blocks this executor thread while waiting. Hold
    // time is bounded by download+extract; contention only happens between
    // concurrent test processes touching the same cache entry.
    let lock_file = tokio::fs::File::create(&lock_path)
        .await
        .map_err(|e| ManagerError::Lock(format!("create lock: {e}")))?;
    AsyncFileExt::lock(&lock_file).map_err(|e| ManagerError::Lock(format!("acquire: {e}")))?;

    // Re-check after acquiring the lock — another process may have downloaded.
    if bin_path.exists() {
        emitter.emit(Status::DriverCacheHit {
            browser,
            version: version.to_string(),
            path: bin_path.clone(),
        });
        return Ok(DriverPath {
            binary: bin_path,
        });
    }

    download_and_extract(client, cfg, browser, version, &dir, emitter).await?;
    emitter.emit(Status::DriverArchiveExtracted {
        browser,
        path: bin_path.clone(),
    });

    Ok(DriverPath {
        binary: bin_path,
    })
}

/// Cache directory of the driver for `(browser, version)` on this platform.
fn cached_driver_dir(cfg: &DownloadConfig, browser: BrowserKind, version: &str) -> PathBuf {
    let platform = match browser {
        BrowserKind::Chrome | BrowserKind::Firefox => chrome_platform(),
        BrowserKind::Edge => edge_platform(),
        BrowserKind::Safari => unreachable!("safari uses the system driver, never cached"),
    };
    cfg.cache_dir.join(browser.cache_dir_name()).join(version).join(platform)
}

/// Where the driver binary for `(browser, version)` is, once downloaded.
fn cached_driver_path(cfg: &DownloadConfig, browser: BrowserKind, version: &str) -> PathBuf {
    cached_driver_dir(cfg, browser, version).join(exe_name(browser))
}

/// The newest driver version with its binary in the cache, of `major_version`
/// if given. Resolves versions in offline mode, without upstream metadata.
fn newest_cached(
    cfg: &DownloadConfig,
    browser: BrowserKind,
    major_version: Option<&str>,
) -> Result<String, ManagerError> {
    let Ok(entries) = std::fs::read_dir(cfg.cache_dir.join(browser.cache_dir_name())) else {
        return Err(ManagerError::Offline);
    };
    entries
        .filter_map(|entry| entry.ok()?.file_name().into_string().ok())
        .filter(|version| major_version.is_none_or(|m| major(version) == m))
        // A directory without the binary is an interrupted download.
        .filter(|version| cached_driver_path(cfg, browser, version).exists())
        .max_by(|a, b| sort_semver(a, b))
        .ok_or(ManagerError::Offline)
}

/// Locate the system-installed `safaridriver`. Currently only macOS ships one.
fn safari_driver_path() -> Result<DriverPath, ManagerError> {
    #[cfg(target_os = "macos")]
    {
        let p = Path::new("/usr/bin/safaridriver");
        if p.exists() {
            return Ok(DriverPath {
                binary: p.to_path_buf(),
            });
        }
        Err(ManagerError::LocalBrowserNotFound {
            browser: "Safari",
            hint: "/usr/bin/safaridriver not found; install Safari and run `safaridriver --enable`",
        })
    }
    #[cfg(not(target_os = "macos"))]
    {
        Err(ManagerError::UnsupportedBrowser("safari (only available on macOS)".to_string()))
    }
}

fn exe_name(browser: BrowserKind) -> String {
    let stem = browser.driver_binary_stem();
    if cfg!(windows) {
        format!("{stem}.exe")
    } else {
        stem.to_string()
    }
}

async fn download_and_extract(
    client: &reqwest::Client,
    cfg: &DownloadConfig,
    browser: BrowserKind,
    version: &str,
    target_dir: &Path,
    emitter: &Emitter,
) -> Result<(), ManagerError> {
    match browser {
        BrowserKind::Chrome => {
            download_chromedriver(client, cfg, version, target_dir, emitter).await
        }
        BrowserKind::Firefox => {
            download_geckodriver(client, cfg, version, target_dir, emitter).await
        }
        BrowserKind::Edge => download_msedgedriver(client, cfg, version, target_dir, emitter).await,
        BrowserKind::Safari => Err(ManagerError::Spawn(
            "Safari is system-managed; ensure_driver() should not have reached download path"
                .into(),
        )),
    }
}

async fn download_msedgedriver(
    client: &reqwest::Client,
    cfg: &DownloadConfig,
    version: &str,
    target_dir: &Path,
    emitter: &Emitter,
) -> Result<(), ManagerError> {
    let platform = edge_platform();
    let url = cfg
        .mirror
        .edge_downloads
        .join(&format!("{version}/edgedriver_{platform}.zip"))
        .map_err(|e| ManagerError::Parse(e.to_string()))?;
    let bytes = fetch_bytes_with_retry(
        client,
        &url,
        cfg.download_timeout,
        BrowserKind::Edge,
        version,
        emitter,
    )
    .await?;
    extract_zip(&bytes, target_dir, BrowserKind::Edge)
}

async fn download_chromedriver(
    client: &reqwest::Client,
    cfg: &DownloadConfig,
    version: &str,
    target_dir: &Path,
    emitter: &Emitter,
) -> Result<(), ManagerError> {
    let index = fetch_chrome_index(client, cfg).await?;
    let entry = index.versions.iter().find(|v| v.version == version).ok_or_else(|| {
        ManagerError::Parse(format!("chromedriver version {version} not in CfT index"))
    })?;
    let platform = chrome_platform();
    let download =
        entry.downloads.chromedriver.iter().find(|d| d.platform == platform).ok_or_else(|| {
            ManagerError::Parse(format!(
                "chromedriver {version} has no download for platform {platform}"
            ))
        })?;
    let url = download
        .url
        .parse::<Url>()
        .map_err(|e| ManagerError::Parse(format!("invalid chromedriver download URL: {e}")))?;
    let bytes = fetch_bytes_with_retry(
        client,
        &url,
        cfg.download_timeout,
        BrowserKind::Chrome,
        version,
        emitter,
    )
    .await?;
    extract_zip(&bytes, target_dir, BrowserKind::Chrome)
}

/// GET a URL into bytes, retrying on transient failures (5xx and network
/// errors). 4xx errors surface immediately — they won't get better with
/// retrying, and retrying could mask a real misconfiguration. Backoff is
/// fixed at 1s, 2s, 4s.
async fn fetch_bytes_with_retry(
    client: &reqwest::Client,
    url: &Url,
    timeout: Duration,
    browser: BrowserKind,
    version: &str,
    emitter: &Emitter,
) -> Result<bytes::Bytes, ManagerError> {
    const MAX_ATTEMPTS: u32 = 3;
    let mut last_err: Option<ManagerError> = None;
    let started = Instant::now();
    emitter.emit(Status::DriverDownloadStarted {
        browser,
        version: version.to_string(),
        url: url.to_string(),
    });
    for attempt in 0..MAX_ATTEMPTS {
        let result: Result<bytes::Bytes, ManagerError> = async {
            let resp = client
                .get(url.clone())
                .header("User-Agent", "thirtyfour-manager")
                .timeout(timeout)
                .send()
                .await?;
            let status = resp.status();
            if status.is_client_error() {
                // 4xx — won't get better with retry; surface immediately.
                return Err(ManagerError::Http(format!("HTTP {status} for {url}")));
            }
            if !status.is_success() {
                // 5xx — retryable.
                return Err(ManagerError::Http(format!("HTTP {status} for {url}")));
            }
            Ok(resp.bytes().await?)
        }
        .await;

        match result {
            Ok(b) => {
                emitter.emit(Status::DriverDownloadComplete {
                    browser,
                    version: version.to_string(),
                    bytes: b.len() as u64,
                    duration: started.elapsed(),
                });
                return Ok(b);
            }
            Err(e @ ManagerError::Http(_)) if is_transient(&e) => {
                emitter.emit(Status::DriverDownloadRetry {
                    attempt: attempt + 1,
                    error: e.to_string(),
                });
                last_err = Some(e);
            }
            Err(e) => return Err(e),
        }

        if attempt + 1 < MAX_ATTEMPTS {
            let backoff = Duration::from_secs(1u64 << attempt); // 1s, 2s, 4s
            tokio::time::sleep(backoff).await;
        }
    }
    Err(last_err.unwrap_or_else(|| ManagerError::Http("retry budget exhausted".into())))
}

/// `true` if the error message indicates a transient failure (5xx, network
/// error, timeout). Used to decide whether to retry.
fn is_transient(err: &ManagerError) -> bool {
    let ManagerError::Http(msg) = err else {
        return false;
    };
    // 5xx codes cover server / gateway / unavailable.
    msg.contains("HTTP 5")
        // reqwest message strings for connect/timeout/connection-closed.
        || msg.contains("operation timed out")
        || msg.contains("connection")
        || msg.contains("dns error")
        || msg.contains("error sending request")
}

/// Own an unpublished sibling of the final binary, including cleanup on failure.
struct StagedDriver {
    path: PathBuf,
    file: Option<std::fs::File>,
    published: bool,
}

impl StagedDriver {
    fn new(target: &Path) -> Result<Self, ManagerError> {
        static NEXT_ID: AtomicU64 = AtomicU64::new(0);
        loop {
            let id = NEXT_ID.fetch_add(1, Ordering::Relaxed);
            let mut name = std::ffi::OsString::from(".");
            name.push(target.file_name().expect("driver path has a file name"));
            name.push(format!(".{}.{id}.tmp", std::process::id()));
            let path = target.with_file_name(name);
            match std::fs::OpenOptions::new().write(true).create_new(true).open(&path) {
                Ok(file) => {
                    return Ok(Self {
                        path,
                        file: Some(file),
                        published: false,
                    });
                }
                Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => continue,
                Err(e) => return Err(ManagerError::Io(e)),
            }
        }
    }
}

impl Drop for StagedDriver {
    fn drop(&mut self) {
        // Windows requires closing the write handle before removing the file.
        drop(self.file.take());
        if !self.published {
            let _ = std::fs::remove_file(&self.path);
        }
    }
}

fn publish_driver(
    reader: &mut impl std::io::Read,
    target: &Path,
    expected_size: u64,
) -> Result<(), ManagerError> {
    let mut staged = StagedDriver::new(target)?;
    let out = staged.file.as_mut().expect("staging file is open");
    let copied = std::io::copy(reader, out).map_err(|e| ManagerError::Extract(e.to_string()))?;
    // A TAR entry can return EOF without an error when its payload is truncated.
    // Preserve the declared-size check that tar::Entry::unpack performs.
    if copied != expected_size {
        return Err(ManagerError::Extract(format!(
            "driver binary truncated: expected {expected_size} bytes, copied {copied}"
        )));
    }
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        out.set_permissions(std::fs::Permissions::from_mode(0o755))?;
    }
    // Close before publication: Windows cannot rename an open writer, and Unix
    // readers must be able to execute the binary as soon as it becomes visible.
    drop(staged.file.take());
    std::fs::rename(&staged.path, target)?;
    staged.published = true;
    Ok(())
}

/// Extract the driver binary for `browser` from a ZIP archive, writing it to
/// `target_dir`.
pub(crate) fn extract_zip(
    bytes: &[u8],
    target_dir: &Path,
    browser: BrowserKind,
) -> Result<(), ManagerError> {
    let cursor = std::io::Cursor::new(bytes);
    let mut zip = zip::ZipArchive::new(cursor).map_err(|e| ManagerError::Extract(e.to_string()))?;
    let exe = exe_name(browser);
    for i in 0..zip.len() {
        let mut entry = zip.by_index(i).map_err(|e| ManagerError::Extract(e.to_string()))?;
        let entry_name = entry.name().to_string();
        let basename = Path::new(&entry_name).file_name().and_then(|s| s.to_str()).unwrap_or("");
        if basename == exe {
            let size = entry.size();
            return publish_driver(&mut entry, &target_dir.join(&exe), size);
        }
    }
    Err(ManagerError::Extract(format!(
        "{exe} not found inside {} archive",
        browser.cache_dir_name()
    )))
}

async fn download_geckodriver(
    client: &reqwest::Client,
    cfg: &DownloadConfig,
    version: &str,
    target_dir: &Path,
    emitter: &Emitter,
) -> Result<(), ManagerError> {
    let url = geckodriver_download_url(cfg, version)?;
    let bytes = fetch_bytes_with_retry(
        client,
        &url,
        cfg.download_timeout,
        BrowserKind::Firefox,
        version,
        emitter,
    )
    .await?;
    if cfg!(windows) {
        extract_zip(&bytes, target_dir, BrowserKind::Firefox)
    } else {
        extract_geckodriver_tar_gz(&bytes, target_dir)
    }
}

fn geckodriver_download_url(cfg: &DownloadConfig, version: &str) -> Result<Url, ManagerError> {
    let v = version.trim_start_matches('v');
    let asset = geckodriver_asset_name(v);
    cfg.mirror
        .geckodriver_downloads
        .join(&format!("v{v}/{asset}"))
        .map_err(|e| ManagerError::Parse(e.to_string()))
}

fn geckodriver_asset_name(version: &str) -> String {
    let suffix = if cfg!(target_os = "windows") {
        if cfg!(target_arch = "aarch64") {
            "win-aarch64.zip"
        } else if cfg!(target_pointer_width = "64") {
            "win64.zip"
        } else {
            "win32.zip"
        }
    } else if cfg!(target_os = "macos") {
        if cfg!(target_arch = "aarch64") {
            "macos-aarch64.tar.gz"
        } else {
            "macos.tar.gz"
        }
    } else if cfg!(target_arch = "aarch64") {
        "linux-aarch64.tar.gz"
    } else {
        "linux64.tar.gz"
    };
    format!("geckodriver-v{version}-{suffix}")
}

fn extract_geckodriver_tar_gz(bytes: &[u8], target_dir: &Path) -> Result<(), ManagerError> {
    let gz = flate2::read::GzDecoder::new(std::io::Cursor::new(bytes));
    let mut archive = tar::Archive::new(gz);
    let exe = exe_name(BrowserKind::Firefox);
    for entry in archive.entries().map_err(|e| ManagerError::Extract(e.to_string()))? {
        let mut entry = entry.map_err(|e| ManagerError::Extract(e.to_string()))?;
        let path = entry.path().map_err(|e| ManagerError::Extract(e.to_string()))?;
        let basename = path.file_name().and_then(|s| s.to_str()).unwrap_or("").to_string();
        if basename == exe {
            let size = entry.size();
            return publish_driver(&mut entry, &target_dir.join(&exe), size);
        }
    }
    Err(ManagerError::Extract(format!("{exe} not found inside geckodriver archive")))
}

/// CfT platform string. Falls back to Linux 64-bit on unknown targets — best
/// effort.
fn chrome_platform() -> &'static str {
    if cfg!(target_os = "macos") {
        if cfg!(target_arch = "aarch64") {
            "mac-arm64"
        } else {
            "mac-x64"
        }
    } else if cfg!(target_os = "windows") {
        if cfg!(target_pointer_width = "64") {
            "win64"
        } else {
            "win32"
        }
    } else {
        if cfg!(target_arch = "aarch64") {
            "linux-arm64"
        } else {
            "linux64"
        }
    }
}

/// msedgedriver platform string. The naming differs from Chrome's CfT scheme.
fn edge_platform() -> &'static str {
    if cfg!(target_os = "macos") {
        if cfg!(target_arch = "aarch64") {
            "mac64_m1"
        } else {
            "mac64"
        }
    } else if cfg!(target_os = "windows") {
        if cfg!(target_arch = "aarch64") {
            "arm64"
        } else if cfg!(target_pointer_width = "64") {
            "win64"
        } else {
            "win32"
        }
    } else {
        "linux64"
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::io::Write;

    #[test]
    fn semver_sort() {
        assert_eq!(sort_semver("126.0.6478.10", "126.0.6478.126"), std::cmp::Ordering::Less);
        assert_eq!(sort_semver("127.0.0.0", "126.99.99.99"), std::cmp::Ordering::Greater);
    }

    #[test]
    fn chrome_platform_known() {
        let p = chrome_platform();
        assert!(["mac-arm64", "mac-x64", "win64", "win32", "linux64"].contains(&p));
    }

    #[test]
    fn edge_platform_known() {
        let p = edge_platform();
        assert!(["mac64_m1", "mac64", "win64", "win32", "arm64", "linux64"].contains(&p));
    }

    #[test]
    fn decode_edge_text_utf16_bom() {
        // bytes: BOM + "126" in UTF-16 LE
        let bytes = [0xFF, 0xFE, 0x31, 0x00, 0x32, 0x00, 0x36, 0x00];
        assert_eq!(decode_edge_text(&bytes).trim(), "126");
    }

    #[test]
    fn decode_edge_text_utf8_fallback() {
        let bytes = b"126.0.6478.126\n";
        assert_eq!(decode_edge_text(bytes).trim(), "126.0.6478.126");
    }

    const DRIVER_SCRIPT: &[u8] = b"#!/bin/sh\nprintf 'driver ready\\n'\n";
    const ORIGINAL_SCRIPT: &[u8] = b"#!/bin/sh\nprintf 'original driver\\n'\n";

    // On Linux, subprocess creation can inherit another test's staging writer
    // until exec, causing ETXTBSY even after the parent closes its handle. Keep
    // tests that write and execute fixture drivers in the same serial group.

    fn assert_driver(path: &Path, content: &[u8], expected_stdout: &[u8]) {
        assert_eq!(std::fs::read(path).unwrap(), content);
        #[cfg(unix)]
        {
            let output = std::process::Command::new(path).output().unwrap();
            assert!(output.status.success());
            assert_eq!(output.stdout, expected_stdout);
        }
        #[cfg(not(unix))]
        let _ = expected_stdout;
    }

    fn install_original(path: &Path) {
        std::fs::write(path, ORIGINAL_SCRIPT).unwrap();
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o755)).unwrap();
        }
    }

    struct PausedReader {
        inner: std::io::Cursor<&'static [u8]>,
        paused: Option<std::sync::mpsc::SyncSender<()>>,
        resume: std::sync::mpsc::Receiver<()>,
    }

    impl std::io::Read for PausedReader {
        fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
            if self.inner.position() < 8 {
                let len = buf.len().min(8 - self.inner.position() as usize);
                return std::io::Read::read(&mut self.inner, &mut buf[..len]);
            }
            // copy() has written the first chunk before requesting another.
            if let Some(paused) = self.paused.take() {
                paused.send(()).unwrap();
                self.resume.recv().unwrap();
            }
            std::io::Read::read(&mut self.inner, buf)
        }
    }

    #[test]
    #[serial_test::serial(driver_publication)]
    fn publish_driver_hides_partial_writes_and_preserves_existing_binary() {
        for existing in [false, true] {
            let dir = tempfile::tempdir().unwrap();
            let target = dir.path().join(exe_name(BrowserKind::Chrome));
            if existing {
                install_original(&target);
            }
            let (paused_tx, paused_rx) = std::sync::mpsc::sync_channel(0);
            let (resume_tx, resume_rx) = std::sync::mpsc::sync_channel(0);
            std::thread::scope(|scope| {
                let writer = scope.spawn(|| {
                    let mut reader = PausedReader {
                        inner: std::io::Cursor::new(DRIVER_SCRIPT),
                        paused: Some(paused_tx),
                        resume: resume_rx,
                    };
                    publish_driver(&mut reader, &target, DRIVER_SCRIPT.len() as u64)
                });
                paused_rx.recv_timeout(Duration::from_secs(10)).unwrap();
                // Release the writer even if observing the cache detects a bug.
                let observed = std::fs::read(&target);
                let original_output = if existing {
                    #[cfg(unix)]
                    {
                        Some(std::process::Command::new(&target).output())
                    }
                    #[cfg(not(unix))]
                    {
                        None::<std::io::Result<std::process::Output>>
                    }
                } else {
                    None
                };
                resume_tx.send(()).unwrap();
                writer.join().unwrap().unwrap();
                if existing {
                    assert_eq!(observed.unwrap(), ORIGINAL_SCRIPT);
                    if let Some(output) = original_output {
                        let output = output.unwrap();
                        assert!(output.status.success());
                        assert_eq!(output.stdout, b"original driver\n");
                    }
                } else {
                    assert_eq!(observed.unwrap_err().kind(), std::io::ErrorKind::NotFound);
                }
            });
            assert_driver(&target, DRIVER_SCRIPT, b"driver ready\n");
            assert_eq!(std::fs::read_dir(dir.path()).unwrap().count(), 1);
        }
    }

    struct FailingReader(std::io::Cursor<&'static [u8]>);

    impl std::io::Read for FailingReader {
        fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
            if self.0.position() == self.0.get_ref().len() as u64 {
                return Err(std::io::Error::other("injected read failure"));
            }
            std::io::Read::read(&mut self.0, buf)
        }
    }

    #[test]
    #[serial_test::serial(driver_publication)]
    fn publish_driver_read_failure_removes_staging_and_preserves_cache() {
        for existing in [false, true] {
            let dir = tempfile::tempdir().unwrap();
            let target = dir.path().join(exe_name(BrowserKind::Chrome));
            if existing {
                install_original(&target);
            }
            let mut reader = FailingReader(std::io::Cursor::new(b"partial driver"));
            assert!(publish_driver(&mut reader, &target, DRIVER_SCRIPT.len() as u64).is_err());
            if existing {
                assert_driver(&target, ORIGINAL_SCRIPT, b"original driver\n");
            } else {
                assert!(!target.exists());
            }
            assert_eq!(std::fs::read_dir(dir.path()).unwrap().count(), usize::from(existing));
        }
    }

    fn zip_fixture(name: &str) -> Vec<u8> {
        let mut zip = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
        let options = zip::write::SimpleFileOptions::default()
            .compression_method(zip::CompressionMethod::Stored);
        zip.start_file(name, options).unwrap();
        zip.write_all(DRIVER_SCRIPT).unwrap();
        zip.finish().unwrap().into_inner()
    }

    fn tar_fixture() -> Vec<u8> {
        let mut tar = tar::Builder::new(Vec::new());
        let mut header = tar::Header::new_gnu();
        header.set_size(DRIVER_SCRIPT.len() as u64);
        header.set_mode(0o644);
        header.set_cksum();
        tar.append_data(&mut header, exe_name(BrowserKind::Firefox), DRIVER_SCRIPT).unwrap();
        tar.into_inner().unwrap()
    }

    fn gzip(bytes: &[u8]) -> Vec<u8> {
        let mut gz = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default());
        gz.write_all(bytes).unwrap();
        gz.finish().unwrap()
    }

    #[test]
    #[serial_test::serial(driver_publication)]
    fn extract_zip_publishes_complete_executable_for_each_browser() {
        for (browser, prefix) in [
            (BrowserKind::Chrome, "chromedriver-linux64/"),
            (BrowserKind::Edge, ""),
            (BrowserKind::Firefox, ""),
        ] {
            let exe = exe_name(browser);
            let archive = zip_fixture(&format!("{prefix}{exe}"));
            let dir = tempfile::tempdir().unwrap();
            extract_zip(&archive, dir.path(), browser).unwrap();
            assert_driver(&dir.path().join(exe), DRIVER_SCRIPT, b"driver ready\n");
            assert_eq!(std::fs::read_dir(dir.path()).unwrap().count(), 1);
        }
    }

    #[test]
    #[serial_test::serial(driver_publication)]
    fn extract_tar_gz_publishes_complete_executable() {
        let dir = tempfile::tempdir().unwrap();
        extract_geckodriver_tar_gz(&gzip(&tar_fixture()), dir.path()).unwrap();
        assert_driver(
            &dir.path().join(exe_name(BrowserKind::Firefox)),
            DRIVER_SCRIPT,
            b"driver ready\n",
        );
        assert_eq!(std::fs::read_dir(dir.path()).unwrap().count(), 1);
    }

    #[test]
    fn extract_corrupt_zip_does_not_publish_or_leave_staging_files() {
        let mut archive = zip_fixture(&exe_name(BrowserKind::Chrome));
        let payload_offset =
            archive.windows(DRIVER_SCRIPT.len()).position(|bytes| bytes == DRIVER_SCRIPT).unwrap();
        archive[payload_offset] ^= 1; // Payload no longer matches the archive's CRC.
        let dir = tempfile::tempdir().unwrap();
        assert!(extract_zip(&archive, dir.path(), BrowserKind::Chrome).is_err());
        assert_eq!(std::fs::read_dir(dir.path()).unwrap().count(), 0);
    }

    #[test]
    fn extract_truncated_tar_gz_does_not_publish_or_leave_staging_files() {
        let mut archive = tar_fixture();
        // Keep the valid header and only part of the declared file payload.
        archive.truncate(512 + 8);
        let dir = tempfile::tempdir().unwrap();
        assert!(extract_geckodriver_tar_gz(&gzip(&archive), dir.path()).is_err());
        assert_eq!(std::fs::read_dir(dir.path()).unwrap().count(), 0);
    }

    #[test]
    fn geckodriver_for_firefox_table() {
        // Latest geckodriver supports Firefox >=128.
        assert_eq!(geckodriver_for_firefox("150.0"), Some("0.36.0"));
        assert_eq!(geckodriver_for_firefox("128.0.1"), Some("0.36.0"));
        // Firefox 115-127: 0.36.0 needs >=128, so we drop to 0.35.0 (>=115, no max).
        assert_eq!(geckodriver_for_firefox("127.0"), Some("0.35.0"));
        assert_eq!(geckodriver_for_firefox("115.0"), Some("0.35.0"));
        // Firefox 102-114: 0.35/0.34 need >=115, so drop to 0.33.0 (102-120).
        assert_eq!(geckodriver_for_firefox("114.0"), Some("0.33.0"));
        assert_eq!(geckodriver_for_firefox("102.5"), Some("0.33.0"));
        // Firefox 91-101: 0.31.0 (91-120).
        assert_eq!(geckodriver_for_firefox("101.0"), Some("0.31.0"));
        assert_eq!(geckodriver_for_firefox("91.0"), Some("0.31.0"));
        // Firefox 78-90: 0.30.0.
        assert_eq!(geckodriver_for_firefox("80.0"), Some("0.30.0"));
        assert_eq!(geckodriver_for_firefox("78.0"), Some("0.30.0"));
        // Firefox 60-77: 0.29.1.
        assert_eq!(geckodriver_for_firefox("70.0"), Some("0.29.1"));
        assert_eq!(geckodriver_for_firefox("60.0"), Some("0.29.1"));
        // Firefox older than anything in the table (< 60): no entry covers it.
        assert_eq!(geckodriver_for_firefox("50.0"), None);
        // Garbage parses as 0 → no entry covers it.
        assert_eq!(geckodriver_for_firefox("nonsense"), None);
    }

    #[test]
    fn transient_error_classification() {
        // 5xx → retry.
        assert!(is_transient(&ManagerError::Http("HTTP 502 Bad Gateway for ...".into())));
        assert!(is_transient(&ManagerError::Http("HTTP 503 Service Unavailable".into())));
        assert!(is_transient(&ManagerError::Http("HTTP 500 Internal Server Error".into())));
        // Network errors → retry.
        assert!(is_transient(&ManagerError::Http("error sending request".into())));
        assert!(is_transient(&ManagerError::Http("operation timed out".into())));
        // 4xx → don't retry.
        assert!(!is_transient(&ManagerError::Http("HTTP 404 Not Found".into())));
        assert!(!is_transient(&ManagerError::Http("HTTP 403 Forbidden".into())));
        // Non-Http error → don't retry.
        assert!(!is_transient(&ManagerError::Parse("bad version".into())));
    }

    #[test]
    fn extract_zip_missing_binary_errors() {
        let mut buf = Vec::new();
        {
            let mut zip = zip::ZipWriter::new(std::io::Cursor::new(&mut buf));
            zip.start_file::<_, ()>("README.txt", Default::default()).unwrap();
            zip.write_all(b"no driver here").unwrap();
            zip.finish().unwrap();
        }
        let dir = tempfile::tempdir().unwrap();
        let err = extract_zip(&buf, dir.path(), BrowserKind::Chrome).unwrap_err();
        assert!(matches!(err, ManagerError::Extract(_)));
    }

    /// A cache holding drivers of `versions`, with mirrors nothing listens on,
    /// so any metadata fetch fails.
    fn cache_with(
        browser: BrowserKind,
        versions: &[&str],
        offline: bool,
    ) -> (tempfile::TempDir, DownloadConfig) {
        let dir = tempfile::tempdir().unwrap();
        let nowhere = Url::parse("http://127.0.0.1:1/").unwrap();
        let cfg = DownloadConfig {
            cache_dir: dir.path().to_path_buf(),
            mirror: Mirror {
                chrome_metadata: nowhere.clone(),
                geckodriver_metadata: nowhere.clone(),
                geckodriver_downloads: nowhere.clone(),
                edge_downloads: nowhere,
            },
            download_timeout: Duration::from_secs(5),
            offline,
        };
        for version in versions {
            let binary = cached_driver_path(&cfg, browser, version);
            std::fs::create_dir_all(binary.parent().unwrap()).unwrap();
            std::fs::write(binary, b"").unwrap();
        }
        (dir, cfg)
    }

    async fn resolve(
        cfg: &DownloadConfig,
        browser: BrowserKind,
        spec: DriverVersion,
        local: Option<&str>,
    ) -> Result<String, ManagerError> {
        resolve_version(&reqwest::Client::new(), cfg, browser, &spec, local, None, &Emitter::new())
            .await
    }

    #[tokio::test]
    async fn cached_chrome_version_resolves_without_index() {
        let (_dir, cfg) = cache_with(BrowserKind::Chrome, &["126.0.6478.126"], false);
        let local = |v: &'static str| {
            resolve(&cfg, BrowserKind::Chrome, DriverVersion::MatchLocalBrowser, Some(v))
        };

        assert_eq!(local("126.0.6478.126").await.unwrap(), "126.0.6478.126");
        // Not in the cache: online, that still takes the index.
        assert!(matches!(local("126.0.6478.10").await, Err(ManagerError::Http(_))));
    }

    #[tokio::test]
    async fn offline_resolves_chrome_from_cache() {
        let (_dir, cfg) = cache_with(
            BrowserKind::Chrome,
            &["126.0.6478.10", "126.0.6478.126", "127.0.6533.50"],
            true,
        );
        // A directory without the binary, as an interrupted download leaves it.
        std::fs::create_dir_all(cached_driver_dir(&cfg, BrowserKind::Chrome, "128.0.6613.0"))
            .unwrap();
        let local = |v: &'static str| {
            resolve(&cfg, BrowserKind::Chrome, DriverVersion::MatchLocalBrowser, Some(v))
        };

        assert_eq!(local("126.0.6478.10").await.unwrap(), "126.0.6478.10");
        // Not cached exactly: the newest driver of the major.
        assert_eq!(local("126.0.6478.99").await.unwrap(), "126.0.6478.126");
        assert!(matches!(local("128.0.6613.0").await, Err(ManagerError::Offline)));

        let exact = resolve(&cfg, BrowserKind::Chrome, DriverVersion::Exact("126".into()), None);
        assert_eq!(exact.await.unwrap(), "126.0.6478.126");
        let latest = resolve(&cfg, BrowserKind::Chrome, DriverVersion::Latest, None);
        assert_eq!(latest.await.unwrap(), "127.0.6533.50");
    }

    #[tokio::test]
    async fn offline_resolves_edge_from_cache() {
        let (_dir, cfg) = cache_with(BrowserKind::Edge, &["126.0.2592.56", "126.0.2592.102"], true);

        let major = resolve(&cfg, BrowserKind::Edge, DriverVersion::Exact("126".into()), None);
        assert_eq!(major.await.unwrap(), "126.0.2592.102");
        let latest = resolve(&cfg, BrowserKind::Edge, DriverVersion::Latest, None);
        assert_eq!(latest.await.unwrap(), "126.0.2592.102");
        let missing = resolve(&cfg, BrowserKind::Edge, DriverVersion::Exact("127".into()), None);
        assert!(matches!(missing.await, Err(ManagerError::Offline)));
        // No chromedriver in the cache at all.
        let chrome = resolve(&cfg, BrowserKind::Chrome, DriverVersion::Latest, None);
        assert!(matches!(chrome.await, Err(ManagerError::Offline)));
    }

    #[tokio::test]
    async fn offline_resolves_firefox_latest_from_cache() {
        let latest = |cfg| resolve(cfg, BrowserKind::Firefox, DriverVersion::Latest, None);

        // Older than the newest geckodriver in the compatibility table.
        let (_dir, cfg) = cache_with(BrowserKind::Firefox, &["0.35.0"], true);
        assert_eq!(latest(&cfg).await.unwrap(), "0.35.0");

        let (_dir, cfg) = cache_with(BrowserKind::Firefox, &["0.34.0", "0.35.0"], true);
        std::fs::create_dir_all(cached_driver_dir(&cfg, BrowserKind::Firefox, "0.36.0")).unwrap();
        assert_eq!(latest(&cfg).await.unwrap(), "0.35.0");

        let (_dir, cfg) = cache_with(BrowserKind::Firefox, &[], true);
        assert!(matches!(latest(&cfg).await, Err(ManagerError::Offline)));
    }
}