ai-usagebar 1.25.0

Omarchy/Waybar widgets + TUI for tracking multi-provider AI plan usage
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
//! Self-update support for the Windows and macOS trays: release discovery,
//! asset selection, checksum verification, and the in-place binary swap.
//!
//! Linux installs get new versions from the AUR, Nix, or cargo-binstall; a
//! Windows install is a zip the user unpacked by hand, and a macOS one is a
//! binary copied somewhere on `PATH`, so nothing would ever tell either that a
//! newer release exists. The tray host polls GitHub's *latest* release once
//! per [`CHECK_INTERVAL`], downloads the per-binary assets the release
//! workflow publishes for its OS and architecture, checks each against its
//! `.sha256` sidecar, and swaps the verified files into the install directory.
//! No compiler is involved on the user's machine.
//!
//! Everything in this module is pure or takes an explicit path, so the whole
//! flow is unit-tested against a temp directory and never touches the network
//! or a real install. The tray host owns the HTTP calls and the UI; this
//! module owns every decision the host must not get wrong twice:
//!
//! - [`parse_release`] / [`is_newer`]: a draft or prerelease is never an
//!   update, and only a strict `X.Y.Z` compares — "newer" must never be a
//!   string comparison, or `1.9.10` loses to `1.10.0`.
//! - [`select_downloads`]: the tray binary is the one doing the updating, so
//!   it is mandatory; the CLI and TUI are nice-to-have and a release that
//!   ships without one of them still updates the tray.
//! - [`verify_sha256`]: nothing lands in the install directory unverified.
//! - [`stage_swap`] / [`sweep_old`]: Windows refuses to overwrite a running
//!   executable but happily lets it be *renamed*, so the live exe becomes
//!   `<name>.old`, the staged file takes its place, and the next start
//!   sweeps the `.old` files once no process holds them any more. macOS
//!   takes the same path: a rename gives the new binary its own inode, where
//!   overwriting the running one in place would get it killed by the kernel's
//!   code-signing check.

use std::fs;
use std::io::Read;
use std::path::{Path, PathBuf};
use std::time::Duration;

use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};

use crate::error::Result;

/// The repository the running binary was built from, as `Cargo.toml`'s
/// `repository` field says. A fork that builds its own tray therefore
/// updates from its own releases without touching code.
pub const SOURCE_REPOSITORY: &str = env!("CARGO_PKG_REPOSITORY");

/// Build-time override for simulating an update on one machine:
/// `AIUB_UPDATE_FEED=http://127.0.0.1:8765/latest.json cargo build ...`
/// makes that binary ask the given URL instead of GitHub and accept plain-HTTP
/// loopback downloads. The release workflow never sets it, so a shipped tray
/// has no runtime switch that could point it elsewhere.
pub const LOCAL_FEED: Option<&str> = option_env!("AIUB_UPDATE_FEED");

/// GitHub's "latest" is the newest non-draft, non-prerelease release, which
/// is exactly the set the tray may install. Polled once per interval.
pub fn latest_release_url() -> Option<String> {
    if let Some(feed) = LOCAL_FEED {
        return Some(feed.to_string());
    }
    latest_release_url_for(SOURCE_REPOSITORY)
}

/// Where a download may come from: HTTPS, or loopback HTTP in a build made
/// with [`LOCAL_FEED`].
pub fn download_url_allowed(url: &str) -> bool {
    download_url_allowed_with(url, LOCAL_FEED.is_some())
}

fn download_url_allowed_with(url: &str, local_feed: bool) -> bool {
    if url.starts_with("https://") {
        return true;
    }
    // Parsed, not prefix-matched: `http://127.0.0.1:1@evil.com/` starts with the
    // loopback prefix but its host is evil.com.
    local_feed
        && reqwest::Url::parse(url).is_ok_and(|parsed| {
            parsed.scheme() == "http"
                && parsed.username().is_empty()
                && parsed.password().is_none()
                && matches!(parsed.host_str(), Some("127.0.0.1" | "localhost"))
        })
}

/// `https://github.com/<owner>/<name>[.git][/]` → the releases/latest API URL.
/// Anything that is not a GitHub repository yields `None`, and the tray
/// reports that it cannot check rather than asking a random host.
pub fn latest_release_url_for(repository: &str) -> Option<String> {
    let path = repository
        .trim()
        .strip_prefix("https://github.com/")?
        .trim_end_matches('/')
        .trim_end_matches(".git");
    let (owner, name) = path.split_once('/')?;
    let valid = |s: &str| {
        !s.is_empty()
            && s.len() <= 100
            && s.chars()
                .all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.'))
    };
    if !valid(owner) || !valid(name) || name.contains('/') {
        return None;
    }
    Some(format!(
        "https://api.github.com/repos/{owner}/{name}/releases/latest"
    ))
}

/// Once an hour: releases are rare, and the unauthenticated GitHub API
/// allows sixty requests an hour per IP — one of them is ours.
pub const CHECK_INTERVAL: Duration = Duration::from_secs(60 * 60);

/// A release exe is a few MiB. Anything reporting more than this is not one
/// of ours and is refused before a single byte is downloaded.
pub const MAX_ASSET_BYTES: u64 = 50 * 1024 * 1024;

/// The three binaries, tray first: it is the one that must update (it runs
/// the updater), the other two are optional extras.
pub const BINARIES: [&str; 3] = ["ai-usagebar-tray", "ai-usagebar", "ai-usagebar-tui"];

/// Longest `html_url` or asset name accepted from the release JSON. Real
/// values are well under a hundred characters; anything longer is not
/// something we want to log, display, or join into a path.
const MAX_FIELD_LEN: usize = 512;

/// One downloadable file of a release. `url` is the `browser_download_url`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Asset {
    pub name: String,
    pub size: u64,
    pub url: String,
}

/// The parts of a GitHub release the updater acts on. `version` is bare
/// (`1.11.0`, never `v1.11.0`) so it compares with `CARGO_PKG_VERSION`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Release {
    pub assets: Vec<Asset>,
    pub html_url: String,
    pub version: String,
}

/// The exe/sidecar pair for one binary, as found in a release.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Download {
    pub binary: &'static str,
    pub exe: Asset,
    pub sha256: Asset,
}

/// Wire shape of `GET /releases/latest` — only the fields we read. Every
/// field but `tag_name` defaults so a schema drift in something we ignore
/// cannot break the update check.
#[derive(Deserialize)]
struct WireRelease {
    #[serde(default)]
    assets: Vec<WireAsset>,
    #[serde(default)]
    draft: bool,
    #[serde(default)]
    html_url: String,
    #[serde(default)]
    prerelease: bool,
    tag_name: Option<String>,
}

#[derive(Deserialize)]
struct WireAsset {
    #[serde(default)]
    browser_download_url: String,
    #[serde(default)]
    name: String,
    #[serde(default)]
    size: u64,
}

/// Parse a release response into what the updater needs.
///
/// A draft or prerelease is an error rather than "not newer": the tray shows
/// the reason, and a silent skip would hide a mis-tagged release forever.
/// Assets are filtered, not rejected wholesale — one odd file in a release
/// must not block the update — but an asset whose name could escape the
/// staging directory (a separator, `..`) is dropped, as is one served from
/// anywhere but HTTPS. `html_url` is the "open release notes" link, which
/// only ever points at GitHub; anything else becomes an empty string so the
/// tray simply shows no link.
pub fn parse_release(json: &str) -> std::result::Result<Release, String> {
    let wire: WireRelease =
        serde_json::from_str(json).map_err(|error| format!("release JSON: {error}"))?;
    if wire.draft || wire.prerelease {
        return Err("prerelease/draft release".to_string());
    }
    let tag = wire
        .tag_name
        .ok_or_else(|| "release JSON has no tag_name".to_string())?;
    let version = tag.strip_prefix('v').unwrap_or(&tag);
    if parse_version(version).is_none() {
        return Err(format!("release tag {tag:?} is not vX.Y.Z"));
    }
    let html_url = if wire.html_url.starts_with("https://github.com/")
        && wire.html_url.len() <= MAX_FIELD_LEN
    {
        wire.html_url
    } else {
        String::new()
    };
    let assets = wire
        .assets
        .into_iter()
        .filter(|asset| asset_name_is_safe(&asset.name))
        .filter(|asset| {
            download_url_allowed(&asset.browser_download_url)
                && asset.browser_download_url.len() <= MAX_FIELD_LEN
        })
        .map(|asset| Asset {
            name: asset.name,
            size: asset.size,
            url: asset.browser_download_url,
        })
        .collect();
    Ok(Release {
        assets,
        html_url,
        version: version.to_string(),
    })
}

/// A name is joined onto the staging and install directories verbatim, so it
/// must be a single plain component.
fn asset_name_is_safe(name: &str) -> bool {
    !name.is_empty()
        && name.len() <= MAX_FIELD_LEN
        && !name.contains(['/', '\\'])
        && !name.contains("..")
        && name != "."
}

/// Strict `X.Y.Z` with numeric components. Pre-release suffixes, build
/// metadata, and two-part versions are all "not a version" here: the release
/// workflow only ever tags `vX.Y.Z`, so anything else is not one of ours.
fn parse_version(text: &str) -> Option<(u64, u64, u64)> {
    let mut parts = text.split('.');
    let major = parts.next()?.parse().ok()?;
    let minor = parts.next()?.parse().ok()?;
    let patch = parts.next()?.parse().ok()?;
    if parts.next().is_some() {
        return None;
    }
    Some((major, minor, patch))
}

/// Numeric semver comparison. A malformed side is `false`: an update the
/// tray cannot reason about is not an update it should offer.
pub fn is_newer(current: &str, candidate: &str) -> bool {
    match (parse_version(current), parse_version(candidate)) {
        (Some(current), Some(candidate)) => candidate > current,
        _ => false,
    }
}

/// The architecture suffix the release workflow uses in asset names.
/// `"unknown"` selects nothing and the tray reports that instead of
/// installing the wrong binary.
pub fn current_arch() -> &'static str {
    if cfg!(target_arch = "x86_64") {
        "x86_64"
    } else if cfg!(target_arch = "aarch64") {
        "aarch64"
    } else {
        "unknown"
    }
}

/// Why the running tray must not replace itself, or `None` when it may.
///
/// `exe` is the path it was started from and `exe_is_link` whether that path is
/// a symbolic link. A package manager links its binaries into place (Homebrew's
/// `bin`), keeps them in its own tree (`Cellar`, `/nix/store`, Scoop's `apps`),
/// and a source build lives in cargo's `target` directory: replacing any of
/// those would fight the tool that owns the file, so the popover offers the
/// release page. `exists` answers whether a file is there; only the Scoop check
/// needs it (see [`scoop_managed`]).
pub fn self_update_blocker(
    exe: &Path,
    exe_is_link: bool,
    exists: impl Fn(&Path) -> bool,
) -> Option<&'static str> {
    if exe_is_link {
        return Some("installed through a link; update it with the tool that installed it");
    }
    if scoop_managed(exe, exists) {
        return Some("managed by Scoop; update it with scoop update");
    }
    let names: Vec<String> = exe
        .components()
        .filter_map(|part| match part {
            std::path::Component::Normal(name) => Some(name.to_string_lossy().into_owned()),
            _ => None,
        })
        .collect();
    if names.iter().any(|name| name == "Cellar") {
        return Some("managed by Homebrew; update it with brew");
    }
    if exe.starts_with("/nix/store") {
        return Some("managed by Nix; update it through your flake or channel");
    }
    // `target/{debug,release}/exe` or `target/<triple>/{debug,release}/exe`.
    let dirs = &names[..names.len().saturating_sub(1)];
    if let Some(profile_at) = dirs.iter().rposition(|d| d == "debug" || d == "release")
        && profile_at + 1 == dirs.len()
        && dirs[..profile_at]
            .iter()
            .rev()
            .take(2)
            .any(|d| d == "target")
    {
        return Some("a cargo build; rebuild it from source");
    }
    None
}

/// Whether `exe` is a Scoop install: `<scoop root>\apps\<app>\<version or current>\<exe>`,
/// with the `install.json` Scoop writes beside every version it installs. Replacing the exe
/// there leaves Scoop's records on the old version (`scoop list`, `scoop status`, the next
/// `scoop update` and `scoop reset` all go wrong), so Scoop has to own the update. The app
/// name is not checked: a fork's bucket can install the tray as `ai-usagebar-dev`.
pub fn scoop_managed(exe: &Path, exists: impl Fn(&Path) -> bool) -> bool {
    let Some(version_dir) = exe.parent() else {
        return false;
    };
    let under_apps = version_dir
        .parent()
        .and_then(Path::parent)
        .and_then(Path::file_name)
        .is_some_and(|name| name.eq_ignore_ascii_case("apps"));
    under_apps && exists(&version_dir.join("install.json"))
}

/// The OS segment of an asset name. `"unknown"` selects nothing, like an
/// unknown architecture.
pub fn current_os() -> &'static str {
    if cfg!(windows) {
        "windows"
    } else if cfg!(target_os = "macos") {
        "macos"
    } else {
        "unknown"
    }
}

/// `{binary}-windows-{arch}.exe` / `{binary}-macos-{arch}` — the bare-binary
/// asset naming in `.github/workflows/release.yml`. Its sidecar is this plus
/// `.sha256`.
pub fn asset_name(binary: &str, os: &str, arch: &str) -> String {
    format!("{binary}-{os}-{arch}{}", exe_suffix(os))
}

/// The file name a binary has once installed: `ai-usagebar-tray.exe` on
/// Windows, `ai-usagebar-tray` elsewhere.
pub fn installed_name(binary: &str, os: &str) -> String {
    format!("{binary}{}", exe_suffix(os))
}

fn exe_suffix(os: &str) -> &'static str {
    if os == "windows" { ".exe" } else { "" }
}

/// Pair each binary with its exe and sidecar, tray first.
///
/// The tray pair is required: a release without it cannot update the thing
/// that is updating, so the whole check fails loudly. The CLI and TUI pairs
/// are skipped when either half is missing — a partial release still updates
/// the tray. A zero-byte or oversized exe is an error for every binary: that
/// is a broken release, not an optional one, and installing a subset would
/// leave a version mix on disk.
pub fn select_downloads(
    release: &Release,
    os: &str,
    arch: &str,
) -> std::result::Result<Vec<Download>, String> {
    let find = |name: &str| release.assets.iter().find(|asset| asset.name == name);
    let mut downloads = Vec::with_capacity(BINARIES.len());
    for binary in BINARIES {
        let required = binary == BINARIES[0];
        let exe_name = asset_name(binary, os, arch);
        let sidecar_name = format!("{exe_name}.sha256");
        let (exe, sha256) = match (find(&exe_name), find(&sidecar_name)) {
            (Some(exe), Some(sha256)) => (exe, sha256),
            _ if required => {
                return Err(format!(
                    "release {} has no {exe_name} + {sidecar_name} pair",
                    release.version
                ));
            }
            _ => continue,
        };
        if exe.size == 0 {
            return Err(format!("{exe_name} is empty"));
        }
        if exe.size > MAX_ASSET_BYTES {
            return Err(format!(
                "{exe_name} is {} bytes, over the {MAX_ASSET_BYTES}-byte limit",
                exe.size
            ));
        }
        downloads.push(Download {
            binary,
            exe: exe.clone(),
            sha256: sha256.clone(),
        });
    }
    Ok(downloads)
}

/// The sidecar the release workflow writes is `"<hex>  <name>"` (the
/// `sha256sum` format, so `sha256sum -c` works on Linux too); accept a bare
/// digest as well. Folded to lowercase so callers compare bytes.
pub fn parse_sha256_sidecar(text: &str) -> std::result::Result<String, String> {
    let digest = text
        .split_whitespace()
        .next()
        .ok_or_else(|| "empty sha256 sidecar".to_string())?;
    if digest.len() != 64 || !digest.bytes().all(|byte| byte.is_ascii_hexdigit()) {
        return Err(format!("sha256 sidecar is not a 64-hex digest: {digest:?}"));
    }
    Ok(digest.to_ascii_lowercase())
}

/// Stream the file through SHA-256 and compare with `expected_hex`
/// (case-insensitive). Streamed rather than read whole: the buffer is a
/// fixed 64 KiB whatever the download turned out to be.
pub fn verify_sha256(path: &Path, expected_hex: &str) -> std::result::Result<(), String> {
    let mut file =
        fs::File::open(path).map_err(|error| format!("open {}: {error}", path.display()))?;
    let mut hasher = Sha256::new();
    let mut buffer = [0u8; 64 * 1024];
    loop {
        let read = file
            .read(&mut buffer)
            .map_err(|error| format!("read {}: {error}", path.display()))?;
        if read == 0 {
            break;
        }
        hasher.update(&buffer[..read]);
    }
    let actual = hex_lower(&hasher.finalize());
    if actual == expected_hex.to_ascii_lowercase() {
        Ok(())
    } else {
        Err(format!(
            "sha256 mismatch for {}: expected {expected_hex}, got {actual}",
            path.display()
        ))
    }
}

fn hex_lower(bytes: &[u8]) -> String {
    use std::fmt::Write;
    let mut text = String::with_capacity(bytes.len() * 2);
    for byte in bytes {
        let _ = write!(text, "{byte:02x}");
    }
    text
}

/// One entry [`stage_swap`] has completed, kept so a later failure can undo it.
struct Swapped {
    dest: PathBuf,
    old: Option<PathBuf>,
    source: PathBuf,
}

/// Move verified staged files into `install_dir`, one `(file name, staged
/// path)` per binary, returning the paths written.
///
/// Every staged path is checked up front so a missing download fails before
/// anything on disk moves. Per entry: an existing `install_dir/<name>` is
/// renamed to `<name>.old` (a stale `.old` from an earlier update is removed
/// first) and the staged file is renamed into place — copy + remove when the
/// staging directory sits on another volume and `rename` refuses. On any
/// failure the entries already swapped are rolled back best-effort: the new
/// file goes back to its staged path and the `.old` returns to its name, so
/// the install never ends up half of one version and half of another.
pub fn stage_swap(
    install_dir: &Path,
    staged: &[(String, PathBuf)],
) -> std::result::Result<Vec<PathBuf>, String> {
    for (name, source) in staged {
        if !asset_name_is_safe(name) {
            return Err(format!("refusing to install a file named {name:?}"));
        }
        if !source.is_file() {
            return Err(format!(
                "staged file {} for {name} does not exist",
                source.display()
            ));
        }
    }
    let mut done: Vec<Swapped> = Vec::with_capacity(staged.len());
    for (name, source) in staged {
        match swap_one(install_dir, name, source) {
            Ok(swapped) => done.push(swapped),
            Err(error) => {
                rollback(&done);
                return Err(error);
            }
        }
    }
    Ok(done.into_iter().map(|swapped| swapped.dest).collect())
}

fn swap_one(install_dir: &Path, name: &str, source: &Path) -> std::result::Result<Swapped, String> {
    let dest = install_dir.join(name);
    let old_path = install_dir.join(format!("{name}.old"));
    let mut old = None;
    if dest.exists() {
        if old_path.exists() {
            fs::remove_file(&old_path)
                .map_err(|error| format!("remove stale {}: {error}", old_path.display()))?;
        }
        fs::rename(&dest, &old_path).map_err(|error| {
            format!(
                "rename {} to {}: {error}",
                dest.display(),
                old_path.display()
            )
        })?;
        old = Some(old_path);
    }
    if let Err(error) = move_file(source, &dest) {
        let _ = fs::remove_file(&dest);
        if let Some(old) = &old {
            let _ = fs::rename(old, &dest);
        }
        return Err(error);
    }
    Ok(Swapped {
        dest,
        old,
        source: source.to_path_buf(),
    })
}

/// `rename`, falling back to copy + remove for a cross-volume move. A
/// half-written copy is removed so the destination is never a truncated exe.
fn move_file(from: &Path, to: &Path) -> std::result::Result<(), String> {
    let Err(rename_error) = fs::rename(from, to) else {
        return Ok(());
    };
    if let Err(copy_error) = fs::copy(from, to) {
        let _ = fs::remove_file(to);
        return Err(format!(
            "move {} to {}: rename failed ({rename_error}), copy failed ({copy_error})",
            from.display(),
            to.display()
        ));
    }
    let _ = fs::remove_file(from);
    Ok(())
}

fn rollback(done: &[Swapped]) {
    for swapped in done.iter().rev() {
        if move_file(&swapped.dest, &swapped.source).is_err() {
            let _ = fs::remove_file(&swapped.dest);
        }
        if let Some(old) = &swapped.old {
            let _ = fs::rename(old, &swapped.dest);
        }
    }
}

/// Delete the `<binary>.old` files a previous [`stage_swap`] left behind for
/// `os` and return how many went. A file still held by a process that has not
/// exited yet stays for the next sweep; nothing else in the directory is
/// touched.
pub fn sweep_old(install_dir: &Path, os: &str) -> usize {
    BINARIES
        .iter()
        .map(|binary| install_dir.join(format!("{}.old", installed_name(binary, os))))
        .filter(|path| path.is_file())
        .filter(|path| fs::remove_file(path).is_ok())
        .count()
}

/// What the tray remembers between checks: when it last asked GitHub, so a
/// restart does not re-poll, and which version the user dismissed, so the
/// same release is not offered again until a newer one appears.
#[derive(Debug, Default, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct UpdateState {
    #[serde(default)]
    pub last_check_ms: i64,
    #[serde(default)]
    pub snoozed_version: Option<String>,
}

impl UpdateState {
    /// Missing or unreadable state is the default: the worst case is one
    /// extra poll and one re-shown prompt, which is the safe direction for a
    /// corrupt sidecar.
    pub fn load_at(path: &Path) -> UpdateState {
        fs::read(path)
            .ok()
            .and_then(|bytes| serde_json::from_slice(&bytes).ok())
            .unwrap_or_default()
    }

    /// Atomic write (tempfile + rename), creating the parent directory.
    pub fn save_at(&self, path: &Path) -> Result<()> {
        let bytes = serde_json::to_vec_pretty(self)?;
        crate::cache::atomic_write(path, &bytes)
    }
}

/// `<cache dir>/ai-usagebar/update.json` — beside the vendor caches and
/// `detect.json`, because it is derived state that is safe to delete.
pub fn default_state_path() -> Result<PathBuf> {
    Ok(crate::cache::xdg_cache_dir()?
        .join("ai-usagebar")
        .join("update.json"))
}

/// Where downloads for one version are staged: `<cache_root>/updates/<version>`.
/// Per version, so an interrupted download of one release never mixes with
/// the next, and the whole directory can be removed after a swap.
pub fn staging_dir(cache_root: &Path, version: &str) -> PathBuf {
    cache_root.join("updates").join(version)
}

#[cfg(test)]
mod tests {
    #[test]
    fn latest_release_url_follows_the_cargo_repository_field() {
        assert_eq!(
            super::latest_release_url_for("https://github.com/akitaonrails/ai-usagebar"),
            Some("https://api.github.com/repos/akitaonrails/ai-usagebar/releases/latest".into())
        );
        assert_eq!(
            super::latest_release_url_for("https://github.com/djalmajr/ai-usagebar.git/"),
            Some("https://api.github.com/repos/djalmajr/ai-usagebar/releases/latest".into())
        );
        assert_eq!(
            super::latest_release_url_for("https://gitlab.com/x/y"),
            None
        );
        assert_eq!(
            super::latest_release_url_for("https://github.com/only-owner"),
            None
        );
        assert_eq!(
            super::latest_release_url_for("https://github.com/o/n/extra"),
            None
        );
        assert_eq!(
            super::latest_release_url_for("https://github.com/o/n%20e"),
            None
        );
        // The build we are in points somewhere valid.
        assert!(
            super::latest_release_url().is_some(),
            "{}",
            super::SOURCE_REPOSITORY
        );
    }

    use super::*;
    use tempfile::TempDir;

    const RELEASE_FIXTURE: &str = r#"{
  "url": "https://api.github.com/repos/akitaonrails/ai-usagebar/releases/300000",
  "html_url": "https://github.com/akitaonrails/ai-usagebar/releases/tag/v1.11.0",
  "id": 300000,
  "tag_name": "v1.11.0",
  "target_commitish": "main",
  "name": "v1.11.0",
  "draft": false,
  "prerelease": false,
  "created_at": "2026-09-01T12:00:00Z",
  "published_at": "2026-09-01T12:05:00Z",
  "assets": [
    {
      "name": "ai-usagebar-linux-x86_64.tar.gz",
      "size": 9000000,
      "content_type": "application/gzip",
      "browser_download_url": "https://github.com/akitaonrails/ai-usagebar/releases/download/v1.11.0/ai-usagebar-linux-x86_64.tar.gz"
    },
    {
      "name": "ai-usagebar-tray-windows-x86_64.exe",
      "size": 6100000,
      "content_type": "application/octet-stream",
      "browser_download_url": "https://github.com/akitaonrails/ai-usagebar/releases/download/v1.11.0/ai-usagebar-tray-windows-x86_64.exe"
    },
    {
      "name": "ai-usagebar-tray-windows-x86_64.exe.sha256",
      "size": 102,
      "content_type": "application/octet-stream",
      "browser_download_url": "https://github.com/akitaonrails/ai-usagebar/releases/download/v1.11.0/ai-usagebar-tray-windows-x86_64.exe.sha256"
    },
    {
      "name": "../evil.exe",
      "size": 10,
      "browser_download_url": "https://github.com/akitaonrails/ai-usagebar/releases/download/v1.11.0/evil.exe"
    },
    {
      "name": "plain-http.exe",
      "size": 10,
      "browser_download_url": "http://example.com/plain-http.exe"
    }
  ]
}"#;

    fn asset(name: &str, size: u64) -> Asset {
        Asset {
            name: name.to_string(),
            size,
            url: format!(
                "https://github.com/akitaonrails/ai-usagebar/releases/download/v1.11.0/{name}"
            ),
        }
    }

    fn pair(binary: &str, size: u64) -> [Asset; 2] {
        let exe = asset_name(binary, "windows", "x86_64");
        [asset(&exe, size), asset(&format!("{exe}.sha256"), 100)]
    }

    fn release_with(assets: Vec<Asset>) -> Release {
        Release {
            assets,
            html_url: String::new(),
            version: "1.11.0".to_string(),
        }
    }

    fn full_release() -> Release {
        release_with(
            BINARIES
                .iter()
                .flat_map(|binary| pair(binary, 5_000_000))
                .collect(),
        )
    }

    #[test]
    fn parse_release_reads_version_url_and_safe_assets() {
        let release = parse_release(RELEASE_FIXTURE).unwrap();

        assert_eq!(release.version, "1.11.0");
        assert_eq!(
            release.html_url,
            "https://github.com/akitaonrails/ai-usagebar/releases/tag/v1.11.0"
        );
        let names: Vec<&str> = release
            .assets
            .iter()
            .map(|asset| asset.name.as_str())
            .collect();
        assert_eq!(
            names,
            vec![
                "ai-usagebar-linux-x86_64.tar.gz",
                "ai-usagebar-tray-windows-x86_64.exe",
                "ai-usagebar-tray-windows-x86_64.exe.sha256",
            ],
            "the traversal name and the plain-http asset are dropped"
        );
        let tray = &release.assets[1];
        assert_eq!(tray.size, 6_100_000);
        assert_eq!(
            tray.url,
            "https://github.com/akitaonrails/ai-usagebar/releases/download/v1.11.0/ai-usagebar-tray-windows-x86_64.exe"
        );
    }

    #[test]
    fn parse_release_accepts_a_bare_tag_and_tolerates_missing_assets() {
        let release =
            parse_release(r#"{"tag_name": "1.11.0", "html_url": "https://evil.example/x"}"#)
                .unwrap();

        assert_eq!(release.version, "1.11.0");
        assert!(release.assets.is_empty());
        assert_eq!(release.html_url, "", "a non-GitHub link is blanked");
    }

    #[test]
    fn parse_release_rejects_prerelease_draft_and_malformed_tags() {
        let prerelease = r#"{"tag_name": "v1.11.0", "prerelease": true}"#;
        assert_eq!(
            parse_release(prerelease).unwrap_err(),
            "prerelease/draft release"
        );

        let draft = r#"{"tag_name": "v1.11.0", "draft": true}"#;
        assert_eq!(
            parse_release(draft).unwrap_err(),
            "prerelease/draft release"
        );

        for tag in ["v1.11", "v1.11.0-rc1", "nightly", "v1.11.0.1", ""] {
            let json = format!(r#"{{"tag_name": "{tag}"}}"#);
            assert!(parse_release(&json).is_err(), "{tag:?} parsed");
        }
        assert!(parse_release(r#"{"draft": false}"#).is_err(), "no tag_name");
        assert!(parse_release("not json").is_err());
    }

    #[test]
    fn is_newer_compares_numerically() {
        assert!(is_newer("1.10.0", "1.11.0"));
        assert!(!is_newer("1.11.0", "1.11.0"), "equal is not newer");
        assert!(!is_newer("1.11.0", "1.10.0"), "older is not newer");
        assert!(is_newer("1.9.10", "1.10.0"), "not a string compare");
        assert!(is_newer("1.10.0", "2.0.0"));
        assert!(is_newer("1.10.0", "1.10.1"));
    }

    #[test]
    fn is_newer_is_false_for_anything_malformed() {
        assert!(!is_newer("1.10.0", "v1.11.0"));
        assert!(!is_newer("1.10.0", "1.11"));
        assert!(!is_newer("1.10.0", "1.11.0-rc1"));
        assert!(!is_newer("garbage", "1.11.0"));
        assert!(!is_newer("", ""));
    }

    #[test]
    fn asset_name_follows_the_release_workflow() {
        assert_eq!(
            asset_name("ai-usagebar-tray", "windows", "x86_64"),
            "ai-usagebar-tray-windows-x86_64.exe"
        );
        assert_eq!(
            asset_name("ai-usagebar-tray", "macos", "aarch64"),
            "ai-usagebar-tray-macos-aarch64"
        );
        assert_eq!(
            installed_name("ai-usagebar-tui", "windows"),
            "ai-usagebar-tui.exe"
        );
        assert_eq!(
            installed_name("ai-usagebar-tui", "macos"),
            "ai-usagebar-tui"
        );
        assert!(["x86_64", "aarch64", "unknown"].contains(&current_arch()));
        assert!(["windows", "macos", "unknown"].contains(&current_os()));
    }

    #[test]
    fn select_downloads_picks_the_assets_for_the_requested_os() {
        let mut assets = full_release().assets;
        for binary in BINARIES {
            let name = asset_name(binary, "macos", "aarch64");
            assets.push(asset(&name, 4_000_000));
            assets.push(asset(&format!("{name}.sha256"), 100));
        }
        let release = release_with(assets);
        let mac = select_downloads(&release, "macos", "aarch64").unwrap();
        assert_eq!(mac[0].exe.name, "ai-usagebar-tray-macos-aarch64");
        let windows = select_downloads(&release, "windows", "x86_64").unwrap();
        assert_eq!(windows[0].exe.name, "ai-usagebar-tray-windows-x86_64.exe");
        // A Windows-only release offers nothing to a Mac.
        assert!(select_downloads(&full_release(), "macos", "aarch64").is_err());
    }

    #[test]
    fn self_update_stays_out_of_package_managers_and_source_trees() {
        use std::path::Path;
        let may = |p: &str| self_update_blocker(Path::new(p), false, |_| false);
        assert_eq!(may("/Users/a/.local/bin/ai-usagebar-tray"), None);
        assert_eq!(may("/Applications/AI Usage/ai-usagebar-tray"), None);
        assert!(
            self_update_blocker(
                Path::new("/opt/homebrew/bin/ai-usagebar-tray"),
                true,
                |_| false
            )
            .is_some()
        );
        assert!(may("/opt/homebrew/Cellar/ai-usagebar/1.21.1/bin/ai-usagebar-tray").is_some());
        assert!(may("/nix/store/0abc-ai-usagebar-1.21.1/bin/ai-usagebar-tray").is_some());
        assert!(may("/Users/a/src/ai-usagebar/target/release/ai-usagebar-tray").is_some());
        assert!(may("/Users/a/src/ai-usagebar/target/debug/ai-usagebar-tray").is_some());
        assert!(
            may("/Users/a/src/ai-usagebar/target/aarch64-apple-darwin/release/ai-usagebar-tray")
                .is_some()
        );
        // A folder merely named "release" is not a cargo profile directory.
        assert_eq!(may("/Users/a/release/ai-usagebar-tray"), None);
        assert_eq!(
            may("/Users/a/target-practice/release/ai-usagebar-tray"),
            None
        );
    }

    #[test]
    fn a_scoop_install_is_left_to_scoop() {
        use std::path::Path;
        // Scoop writes install.json beside each version it installs; the probe stands in for it.
        let scoop = |p: &Path| p.ends_with("install.json");
        let user = "C:/Users/a/scoop/apps/ai-usagebar/current/ai-usagebar-tray.exe";
        let version = "C:/Users/a/scoop/apps/ai-usagebar/1.24.0/ai-usagebar-tray.exe";
        let global = "C:/ProgramData/scoop/apps/ai-usagebar/current/ai-usagebar-tray.exe";
        let fork = "D:/tools/scoop/apps/ai-usagebar-dev/current/ai-usagebar-tray.exe";
        for exe in [user, version, global, fork] {
            assert!(scoop_managed(Path::new(exe), scoop), "{exe}");
            assert_eq!(
                self_update_blocker(Path::new(exe), false, scoop),
                Some("managed by Scoop; update it with scoop update"),
                "{exe}"
            );
        }
        // The folder name is compared the way Windows compares it.
        assert!(scoop_managed(
            Path::new("C:/Users/a/scoop/Apps/ai-usagebar/current/ai-usagebar-tray.exe"),
            scoop
        ));
    }

    #[test]
    fn a_folder_that_only_looks_like_scoop_still_updates_itself() {
        use std::path::Path;
        let exe = Path::new("D:/apps/ai-usagebar/1.24.0/ai-usagebar-tray.exe");
        // No install.json beside the exe: an unzipped release under a folder named "apps".
        assert!(!scoop_managed(exe, |_| false));
        assert_eq!(self_update_blocker(exe, false, |_| false), None);
        // install.json alone is not enough without Scoop's apps\<app>\<version> layout.
        let has_manifest = |p: &Path| p.ends_with("install.json");
        for exe in [
            "C:/Users/a/AI Usage/ai-usagebar-tray.exe",
            "C:/Users/a/scoop/ai-usagebar/current/ai-usagebar-tray.exe",
            "ai-usagebar-tray.exe",
        ] {
            assert!(!scoop_managed(Path::new(exe), has_manifest), "{exe}");
        }
    }

    #[test]
    fn scoop_is_detected_from_the_install_json_on_disk() {
        let tmp = tempfile::tempdir().unwrap();
        let version_dir = tmp
            .path()
            .join("scoop")
            .join("apps")
            .join("ai-usagebar")
            .join("1.24.0");
        std::fs::create_dir_all(&version_dir).unwrap();
        let exe = version_dir.join("ai-usagebar-tray.exe");
        let on_disk = |p: &std::path::Path| p.is_file();
        assert!(!scoop_managed(&exe, on_disk));
        std::fs::write(version_dir.join("install.json"), b"{}").unwrap();
        assert!(scoop_managed(&exe, on_disk));
    }

    #[test]
    fn loopback_http_is_a_download_source_only_for_a_local_feed_build() {
        assert!(download_url_allowed_with("https://github.com/x", false));
        assert!(!download_url_allowed_with("http://127.0.0.1:8765/a", false));
        assert!(download_url_allowed_with("http://127.0.0.1:8765/a", true));
        assert!(download_url_allowed_with("http://localhost:8765/a", true));
        assert!(!download_url_allowed_with("http://example.com/a", true));
        assert!(!download_url_allowed_with(
            "http://127.0.0.1.evil.com/a",
            true
        ));
        assert!(!download_url_allowed_with(
            "http://127.0.0.1:1@evil.com/a",
            true
        ));
        assert!(!download_url_allowed_with(
            "http://user:pw@127.0.0.1:8765/a",
            true
        ));
    }

    #[test]
    fn select_downloads_pairs_all_three_binaries_tray_first() {
        let downloads = select_downloads(&full_release(), "windows", "x86_64").unwrap();

        let binaries: Vec<&str> = downloads.iter().map(|d| d.binary).collect();
        assert_eq!(binaries, BINARIES.to_vec());
        for download in &downloads {
            assert_eq!(
                download.exe.name,
                asset_name(download.binary, "windows", "x86_64")
            );
            assert_eq!(
                download.sha256.name,
                format!("{}.sha256", download.exe.name)
            );
        }
    }

    #[test]
    fn select_downloads_requires_the_tray_pair() {
        let mut assets: Vec<Asset> = pair("ai-usagebar", 5_000_000).to_vec();
        assets.extend(pair("ai-usagebar-tui", 5_000_000));
        let error = select_downloads(&release_with(assets), "windows", "x86_64").unwrap_err();
        assert!(
            error.contains("ai-usagebar-tray-windows-x86_64.exe"),
            "{error}"
        );

        // Exe without its sidecar is just as missing.
        let [tray_exe, _] = pair("ai-usagebar-tray", 5_000_000);
        assert!(select_downloads(&release_with(vec![tray_exe]), "windows", "x86_64").is_err());

        // Wrong arch: nothing matches.
        assert!(select_downloads(&full_release(), "windows", "aarch64").is_err());
    }

    #[test]
    fn select_downloads_skips_an_incomplete_optional_pair() {
        let mut assets: Vec<Asset> = pair("ai-usagebar-tray", 5_000_000).to_vec();
        assets.extend(pair("ai-usagebar-tui", 5_000_000));
        let [cli_exe, _] = pair("ai-usagebar", 5_000_000);
        assets.push(cli_exe); // sidecar missing → skipped

        let downloads = select_downloads(&release_with(assets), "windows", "x86_64").unwrap();

        let binaries: Vec<&str> = downloads.iter().map(|d| d.binary).collect();
        assert_eq!(binaries, vec!["ai-usagebar-tray", "ai-usagebar-tui"]);
    }

    #[test]
    fn select_downloads_rejects_empty_and_oversized_exes() {
        let mut assets: Vec<Asset> = pair("ai-usagebar-tray", MAX_ASSET_BYTES + 1).to_vec();
        let error =
            select_downloads(&release_with(assets.clone()), "windows", "x86_64").unwrap_err();
        assert!(error.contains("over the"), "{error}");

        assets = pair("ai-usagebar-tray", 0).to_vec();
        let error = select_downloads(&release_with(assets), "windows", "x86_64").unwrap_err();
        assert!(error.contains("empty"), "{error}");

        // An optional exe with a bad size is a broken release, not a skip.
        let mut assets: Vec<Asset> = pair("ai-usagebar-tray", 5_000_000).to_vec();
        assets.extend(pair("ai-usagebar-tui", MAX_ASSET_BYTES + 1));
        assert!(select_downloads(&release_with(assets), "windows", "x86_64").is_err());

        // Exactly the limit is still allowed.
        let assets: Vec<Asset> = pair("ai-usagebar-tray", MAX_ASSET_BYTES).to_vec();
        assert!(select_downloads(&release_with(assets), "windows", "x86_64").is_ok());
    }

    #[test]
    fn parse_sha256_sidecar_accepts_both_formats_and_folds_case() {
        let hex = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";

        assert_eq!(
            parse_sha256_sidecar(&format!("{hex}  ai-usagebar-tray-windows-x86_64.exe\n")).unwrap(),
            hex
        );
        assert_eq!(parse_sha256_sidecar(hex).unwrap(), hex);
        assert_eq!(parse_sha256_sidecar(&format!("  {hex}\r\n")).unwrap(), hex);
        assert_eq!(
            parse_sha256_sidecar(&hex.to_ascii_uppercase()).unwrap(),
            hex,
            "uppercase is folded"
        );
    }

    #[test]
    fn parse_sha256_sidecar_rejects_garbage() {
        assert!(parse_sha256_sidecar("").is_err());
        assert!(parse_sha256_sidecar("   \n").is_err());
        assert!(
            parse_sha256_sidecar("deadbeef  name.exe").is_err(),
            "too short"
        );
        assert!(
            parse_sha256_sidecar(&"zz".repeat(32)).is_err(),
            "right length, not hex"
        );
        assert!(
            parse_sha256_sidecar(
                "name.exe  e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
            )
            .is_err(),
            "name first is not the format"
        );
    }

    #[test]
    fn verify_sha256_streams_the_file_and_detects_mismatch() {
        let dir = TempDir::new().unwrap();
        let path = dir.path().join("blob.bin");
        let contents: Vec<u8> = (0..200_000u32).map(|i| (i % 251) as u8).collect();
        std::fs::write(&path, &contents).unwrap();
        let expected = hex_lower(&Sha256::digest(&contents));

        assert_eq!(verify_sha256(&path, &expected), Ok(()));
        assert_eq!(
            verify_sha256(&path, &expected.to_ascii_uppercase()),
            Ok(()),
            "case-insensitive"
        );

        let wrong = format!("{}{}", &expected[1..], "0");
        let error = verify_sha256(&path, &wrong).unwrap_err();
        assert!(error.contains("mismatch"), "{error}");

        assert!(verify_sha256(&dir.path().join("absent"), &expected).is_err());
    }

    #[test]
    fn stage_swap_replaces_the_exe_and_keeps_the_old_one() {
        let dir = TempDir::new().unwrap();
        let install = dir.path().join("install");
        let staging = dir.path().join("staging");
        std::fs::create_dir_all(&install).unwrap();
        std::fs::create_dir_all(&staging).unwrap();
        let name = "ai-usagebar-tray.exe";
        std::fs::write(install.join(name), b"v1").unwrap();
        let staged = staging.join(name);
        std::fs::write(&staged, b"v2").unwrap();

        let written = stage_swap(&install, &[(name.to_string(), staged.clone())]).unwrap();

        assert_eq!(written, vec![install.join(name)]);
        assert_eq!(std::fs::read(install.join(name)).unwrap(), b"v2");
        assert_eq!(
            std::fs::read(install.join("ai-usagebar-tray.exe.old")).unwrap(),
            b"v1"
        );
        assert!(!staged.exists(), "the staged file was moved, not copied");

        // A second update replaces the stale `.old` rather than failing on it.
        std::fs::write(&staged, b"v3").unwrap();
        stage_swap(&install, &[(name.to_string(), staged.clone())]).unwrap();
        assert_eq!(std::fs::read(install.join(name)).unwrap(), b"v3");
        assert_eq!(
            std::fs::read(install.join("ai-usagebar-tray.exe.old")).unwrap(),
            b"v2"
        );
    }

    #[test]
    fn stage_swap_installs_a_binary_that_was_not_there_before() {
        let dir = TempDir::new().unwrap();
        let install = dir.path().join("install");
        std::fs::create_dir_all(&install).unwrap();
        let staged = dir.path().join("ai-usagebar-tui.exe");
        std::fs::write(&staged, b"new").unwrap();

        stage_swap(&install, &[("ai-usagebar-tui.exe".to_string(), staged)]).unwrap();

        assert_eq!(
            std::fs::read(install.join("ai-usagebar-tui.exe")).unwrap(),
            b"new"
        );
        assert!(!install.join("ai-usagebar-tui.exe.old").exists());
    }

    #[test]
    fn stage_swap_with_a_missing_staged_file_touches_nothing() {
        let dir = TempDir::new().unwrap();
        let install = dir.path().join("install");
        std::fs::create_dir_all(&install).unwrap();
        std::fs::write(install.join("ai-usagebar-tray.exe"), b"v1").unwrap();
        std::fs::write(install.join("ai-usagebar.exe"), b"v1").unwrap();
        let tray_staged = dir.path().join("ai-usagebar-tray.exe");
        std::fs::write(&tray_staged, b"v2").unwrap();

        let error = stage_swap(
            &install,
            &[
                ("ai-usagebar-tray.exe".to_string(), tray_staged.clone()),
                (
                    "ai-usagebar.exe".to_string(),
                    dir.path().join("never-downloaded.exe"),
                ),
            ],
        )
        .unwrap_err();

        assert!(error.contains("does not exist"), "{error}");
        assert_eq!(
            std::fs::read(install.join("ai-usagebar-tray.exe")).unwrap(),
            b"v1"
        );
        assert_eq!(
            std::fs::read(install.join("ai-usagebar.exe")).unwrap(),
            b"v1"
        );
        assert!(!install.join("ai-usagebar-tray.exe.old").exists());
        assert!(
            tray_staged.exists(),
            "the good download is kept for a retry"
        );
    }

    #[test]
    fn stage_swap_rolls_back_entries_already_swapped_when_a_later_one_fails() {
        let dir = TempDir::new().unwrap();
        let install = dir.path().join("install");
        std::fs::create_dir_all(&install).unwrap();
        std::fs::write(install.join("ai-usagebar-tray.exe"), b"v1").unwrap();
        std::fs::write(install.join("ai-usagebar.exe"), b"v1").unwrap();
        // A stale `.old` that is a non-empty directory cannot be removed, so
        // the second entry fails after the first has already been swapped.
        let blocker = install.join("ai-usagebar.exe.old");
        std::fs::create_dir_all(&blocker).unwrap();
        std::fs::write(blocker.join("keep"), b"x").unwrap();
        let tray_staged = dir.path().join("ai-usagebar-tray.exe");
        let cli_staged = dir.path().join("ai-usagebar.exe");
        std::fs::write(&tray_staged, b"v2").unwrap();
        std::fs::write(&cli_staged, b"v2").unwrap();

        let result = stage_swap(
            &install,
            &[
                ("ai-usagebar-tray.exe".to_string(), tray_staged.clone()),
                ("ai-usagebar.exe".to_string(), cli_staged.clone()),
            ],
        );

        assert!(result.is_err());
        assert_eq!(
            std::fs::read(install.join("ai-usagebar-tray.exe")).unwrap(),
            b"v1",
            "the tray swap was undone"
        );
        assert!(!install.join("ai-usagebar-tray.exe.old").exists());
        assert_eq!(
            std::fs::read(&tray_staged).unwrap(),
            b"v2",
            "staged file restored"
        );
        assert_eq!(
            std::fs::read(install.join("ai-usagebar.exe")).unwrap(),
            b"v1"
        );
        assert_eq!(std::fs::read(&cli_staged).unwrap(), b"v2");
    }

    #[test]
    fn stage_swap_refuses_names_that_leave_the_install_dir() {
        let dir = TempDir::new().unwrap();
        let staged = dir.path().join("x.exe");
        std::fs::write(&staged, b"x").unwrap();

        for name in ["../x.exe", "sub/x.exe", "sub\\x.exe", "", ".."] {
            let error = stage_swap(dir.path(), &[(name.to_string(), staged.clone())]).unwrap_err();
            assert!(error.contains("refusing"), "{name:?}: {error}");
        }
    }

    #[test]
    fn sweep_old_removes_only_the_binaries_old_files() {
        let dir = TempDir::new().unwrap();
        for name in [
            "ai-usagebar-tray.exe.old",
            "ai-usagebar.exe.old",
            "ai-usagebar-tray.exe",
            "notes.old",
            "config.toml",
        ] {
            std::fs::write(dir.path().join(name), b"x").unwrap();
        }
        std::fs::create_dir(dir.path().join("dir.exe.old")).unwrap();

        assert_eq!(sweep_old(dir.path(), "windows"), 2);

        let mut remaining: Vec<String> = std::fs::read_dir(dir.path())
            .unwrap()
            .map(|entry| entry.unwrap().file_name().to_string_lossy().into_owned())
            .collect();
        remaining.sort();
        assert_eq!(
            remaining,
            vec![
                "ai-usagebar-tray.exe",
                "config.toml",
                "dir.exe.old",
                "notes.old"
            ]
        );

        assert_eq!(sweep_old(dir.path(), "windows"), 0, "nothing left to sweep");
        assert_eq!(sweep_old(&dir.path().join("absent"), "windows"), 0);
    }

    #[test]
    fn sweep_old_on_macos_removes_the_suffixless_leftovers() {
        let dir = TempDir::new().unwrap();
        for name in ["ai-usagebar-tray.old", "ai-usagebar-tray", "notes.old"] {
            std::fs::write(dir.path().join(name), b"x").unwrap();
        }
        assert_eq!(sweep_old(dir.path(), "macos"), 1);
        assert!(dir.path().join("ai-usagebar-tray").is_file());
        assert!(dir.path().join("notes.old").is_file());
    }

    #[test]
    fn update_state_round_trips_and_a_corrupt_file_is_the_default() {
        let dir = TempDir::new().unwrap();
        let path = dir.path().join("nested").join("update.json");
        let state = UpdateState {
            last_check_ms: 1_757_246_400_000,
            snoozed_version: Some("1.11.0".to_string()),
        };

        state.save_at(&path).unwrap();

        assert_eq!(UpdateState::load_at(&path), state);
        let text = std::fs::read_to_string(&path).unwrap();
        assert!(text.contains("\"snoozed_version\": \"1.11.0\""), "{text}");

        assert_eq!(
            UpdateState::load_at(&dir.path().join("absent.json")),
            UpdateState::default()
        );
        let corrupt = dir.path().join("corrupt.json");
        std::fs::write(&corrupt, "{\"last_check_ms\": ").unwrap();
        assert_eq!(UpdateState::load_at(&corrupt), UpdateState::default());

        // Missing fields default rather than failing the whole load.
        let partial = dir.path().join("partial.json");
        std::fs::write(&partial, "{\"last_check_ms\": 5}").unwrap();
        assert_eq!(
            UpdateState::load_at(&partial),
            UpdateState {
                last_check_ms: 5,
                snoozed_version: None,
            }
        );
    }

    #[test]
    fn staging_dir_is_per_version_under_the_cache_root() {
        let root = Path::new("cache");
        assert_eq!(
            staging_dir(root, "1.11.0"),
            Path::new("cache").join("updates").join("1.11.0")
        );
    }
}