eclipse-core 0.15.1

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

use crate::config::{state_dir, EnvFn, Track, UpdateCheck, UpdateConfig};
use crate::error::{Error, Result};
use crate::http::{self, Reach};
use serde::{Deserialize, Serialize};
use std::fmt;
use std::path::{Path, PathBuf};
use std::time::Duration;

pub const MARKER_FILE: &str = "install.json";
pub const CACHE_FILE: &str = "update.json";

/// The public repository's latest commit on `main`, which is the branch releases are cut from.
/// GitHub answers with the bare id when asked for `application/vnd.github.sha`, and with a JSON
/// object carrying `sha` otherwise; both are understood so `[update] remote` can point at either
/// kind of server.
pub const DEFAULT_LATEST_URL: &str = "https://api.github.com/repos/mmhorda/eclipse/commits/main";

/// The same question about `develop`, for a source install that follows that track
/// (`[update] track = "develop"`): the commits that are coming, not the ones that were released.
pub const DEVELOP_LATEST_URL: &str = "https://api.github.com/repos/mmhorda/eclipse/commits/develop";

/// The commit question for a track: the branch the track names, unless the user pointed
/// `[update] remote` somewhere of their own — an explicit URL is the escape hatch, and a track
/// must not quietly reroute it.
fn latest_question(cfg: &UpdateConfig) -> (&str, Reach) {
    match cfg.remote.as_deref() {
        Some(remote) => (remote, Reach::Anywhere),
        None => match cfg.track {
            Track::Release => (DEFAULT_LATEST_URL, Reach::Public),
            Track::Develop => (DEVELOP_LATEST_URL, Reach::Public),
        },
    }
}

/// The newest release. A `release` install compares a tag with a version, not a commit with a
/// commit, so it asks a different question; the answer carries the tag and the asset URLs that
/// `eclipse upgrade` downloads from, which is why a mirror can stand in for GitHub here too.
pub const DEFAULT_RELEASES_URL: &str =
    "https://api.github.com/repos/mmhorda/eclipse/releases/latest";

/// The one asset a Linux install can use. Named rather than guessed from `uname`: a release with
/// no matching asset is a refusal that lists what the release does carry.
pub const TARBALL_SUFFIX: &str = "-x86_64-unknown-linux-gnu.tar.gz";

/// The asset that says which bytes the tarball should be.
pub const SUMS_NAME: &str = "SHA256SUMS";

/// A release answer is a tag, a page and a handful of assets; a body larger than this is
/// something else.
const MAX_RELEASE_BYTES: usize = 64 * 1024;

/// Asking for a release is two round trips' worth of latency on a bad day, not a 2 s notice.
pub const RELEASE_TIMEOUT: Duration = Duration::from_secs(20);

/// The whole budget for one check: name resolution, connect, and reading the answer.
pub const CHECK_TIMEOUT: Duration = Duration::from_secs(2);

/// An answer longer than this is not a commit id; reading stops here.
const MAX_ANSWER_BYTES: usize = 8 * 1024;

#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum Channel {
    /// Built from a checkout by `install.sh`. Upgraded by `git pull` and a rebuild.
    Source,
    /// Installed from an unpacked release tarball. Upgraded by downloading the next tag's
    /// tarball and swapping the binaries in place.
    Release,
}

impl Channel {
    pub fn label(self) -> &'static str {
        match self {
            Channel::Source => "source",
            Channel::Release => "release",
        }
    }
}

/// A release version: three numbers, no pre-release. The workflow refuses a tag that disagrees
/// with `Cargo.toml`, and `Cargo.toml` carries no pre-release, so a fourth field would be a
/// parser nobody can reach from a real release.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub struct Version {
    pub major: u64,
    pub minor: u64,
    pub patch: u64,
}

impl Version {
    /// `v0.2.1` or `0.2.1`; anything else is `None` rather than a guess.
    pub fn parse(text: &str) -> Option<Version> {
        let text = text.trim();
        let text = text.strip_prefix('v').unwrap_or(text);
        let mut parts = text.split('.');
        let major = parts.next()?.parse().ok()?;
        let minor = parts.next()?.parse().ok()?;
        // A suffix on the last number is dropped: it is not part of what orders two releases,
        // and no tag that survives the release workflow carries one.
        let patch = parts.next()?.split(['-', '+']).next()?.parse().ok()?;
        if parts.next().is_some() {
            return None;
        }
        Some(Version {
            major,
            minor,
            patch,
        })
    }
}

impl fmt::Display for Version {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}.{}.{}", self.major, self.minor, self.patch)
    }
}

/// One release, as the API describes it: enough to fetch and verify the one asset this machine
/// can use, and nothing else.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Release {
    /// The tag, `v` included, because that is how the release is named.
    pub tag: String,
    pub version: Version,
    pub tarball_url: String,
    pub tarball_name: String,
    pub sums_url: String,
    /// The release page, for a message that has to say what a major jump contains.
    pub page: Option<String>,
}

/// Read a release answer. The assets are the API's, not a URL built from a template: a tag can
/// be republished, an asset name can change with the platform rule, and a mirror answers the
/// same shape with its own URLs.
pub fn parse_release(body: &str) -> std::result::Result<Release, String> {
    let value: serde_json::Value =
        serde_json::from_str(body).map_err(|e| format!("not a release object: {e}"))?;
    let tag = value
        .get("tag_name")
        .and_then(|v| v.as_str())
        .ok_or("the answer carries no tag_name")?
        .trim()
        .to_string();
    let version =
        Version::parse(&tag).ok_or_else(|| format!("tag {tag:?} is not vMAJOR.MINOR.PATCH"))?;
    let assets = value
        .get("assets")
        .and_then(|v| v.as_array())
        .ok_or("the answer carries no assets")?;
    let find = |want: &dyn Fn(&str) -> bool| -> Option<(String, String)> {
        assets.iter().find_map(|a| {
            let name = a.get("name")?.as_str()?;
            if !want(name) {
                return None;
            }
            let url = a.get("browser_download_url")?.as_str()?.to_string();
            Some((name.to_string(), url))
        })
    };
    let (tarball_name, tarball_url) = find(&|n| n.ends_with(TARBALL_SUFFIX)).ok_or_else(|| {
        format!(
            "{tag} has no {TARBALL_SUFFIX} asset (it carries: {})",
            asset_names(assets)
        )
    })?;
    let sums_url = find(&|n| n == SUMS_NAME)
        .map(|(_, url)| url)
        .ok_or_else(|| {
            format!("{tag} has no {SUMS_NAME} asset, so a download could not be checked")
        })?;
    Ok(Release {
        tag,
        version,
        tarball_url,
        tarball_name,
        sums_url,
        page: value
            .get("html_url")
            .and_then(|v| v.as_str())
            .map(str::to_string),
    })
}

fn asset_names(assets: &[serde_json::Value]) -> String {
    let names: Vec<&str> = assets
        .iter()
        .filter_map(|a| a.get("name").and_then(|n| n.as_str()))
        .collect();
    if names.is_empty() {
        "nothing".to_string()
    } else {
        names.join(", ")
    }
}

/// `<state>/install.json`: what `install.sh` recorded.
#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
pub struct InstallMarker {
    pub channel: Channel,
    /// Where the binaries live: `<prefix>/bin/eclipse`.
    pub prefix: PathBuf,
    /// The checkout that was built. Recorded rather than derived from `prefix`, because the
    /// two have nothing to do with each other: `--prefix /usr/local` says where the binaries
    /// went, not where the sources are. `None` for a release install, which has no checkout.
    #[serde(default)]
    pub workspace: Option<PathBuf>,
    /// `git rev-parse HEAD` of the checkout at install time; `None` for an install that had no
    /// git checkout, such as an unpacked tarball.
    #[serde(default)]
    pub commit: Option<String>,
    /// RFC 3339, UTC.
    pub installed_at: String,
    /// `release` or `debug`: which cargo profile `install.sh` built, so an upgrade installs
    /// the same kind rather than quietly switching.
    #[serde(default)]
    pub build: Option<String>,
    /// The version the binaries report, without the `v`. Written for both channels: it is what
    /// a release install compares against a newer tag, and what a refusal can name when the
    /// marker is older than this field.
    #[serde(default)]
    pub version: Option<String>,
}

impl InstallMarker {
    /// Where the marker is, or `None` when HOME and the XDG variables leave no state directory.
    ///
    /// Always the plain state directory, never a profile's: an install belongs to the machine
    /// user, not to a profile, and `install.sh` has no notion of profiles.
    pub fn path(env: EnvFn) -> Option<PathBuf> {
        state_dir(env).map(|d| d.join(MARKER_FILE))
    }

    /// Read the marker at `path`. `None` means there is no such file, which is a state to report
    /// (the caller says what to do), not an error; a file that is there but unreadable or not
    /// understood is an error naming the file.
    pub fn load(path: &Path) -> Result<Option<InstallMarker>> {
        let text = match std::fs::read_to_string(path) {
            Ok(t) => t,
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
            Err(e) => return Err(Error::io(path, e)),
        };
        serde_json::from_str(&text)
            .map(Some)
            .map_err(|e| Error::Parse {
                path: path.to_path_buf(),
                message: format!("{e} (run install.sh again to rewrite it)"),
            })
    }
}

/// `<state>/update.json`: the last time the repository was asked, and what it said.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default)]
pub struct UpdateCache {
    /// Unix seconds of the last *attempt*. A failure counts: a server that is down is not asked
    /// again until the period is up, or every run would pay for the question.
    pub checked_at: u64,
    /// The latest commit the last successful answer named.
    pub latest: Option<String>,
    /// The commit the notice was last printed for, so it is said once and not on every run.
    pub notified: Option<String>,
}

impl UpdateCache {
    /// A missing or unreadable cache is an empty one: it only ever saves a request.
    pub fn load(path: &Path) -> UpdateCache {
        std::fs::read_to_string(path)
            .ok()
            .and_then(|t| serde_json::from_str(&t).ok())
            .unwrap_or_default()
    }

    /// Best effort and atomic (write beside, rename over): a cache that cannot be written
    /// costs a request next time, and must not cost a run.
    pub fn save(&self, path: &Path) {
        let Ok(text) = serde_json::to_string_pretty(self) else {
            return;
        };
        if let Some(dir) = path.parent() {
            if std::fs::create_dir_all(dir).is_err() {
                return;
            }
        }
        let tmp = path.with_extension(format!("json.{}.tmp", std::process::id()));
        if std::fs::write(&tmp, text + "\n").is_err() || std::fs::rename(&tmp, path).is_err() {
            let _ = std::fs::remove_file(&tmp);
        }
    }

    /// Whether the repository should be asked now.
    pub fn is_due(&self, check: UpdateCheck, now_secs: u64) -> bool {
        match check.period_secs() {
            None => false,
            Some(period) => now_secs.saturating_sub(self.checked_at) >= period,
        }
    }
}

/// A commit id out of an answer: the whole body, or a JSON object's `sha`.
pub fn parse_latest(body: &str) -> Option<String> {
    let is_id = |s: &str| matches!(s.len(), 40 | 64) && s.bytes().all(|b| b.is_ascii_hexdigit());
    let bare = body.trim();
    if is_id(bare) {
        return Some(bare.to_ascii_lowercase());
    }
    let value: serde_json::Value = serde_json::from_str(bare).ok()?;
    let sha = value.get("sha")?.as_str()?.trim();
    is_id(sha).then(|| sha.to_ascii_lowercase())
}

/// One `GET`, read to a cap, inside one deadline. Both questions this module asks go through
/// here so a mirror, a proxy and a captive portal behave identically for each of them.
async fn get_body(
    raw: &str,
    reach: Reach,
    accept: &str,
    timeout: Duration,
    cap: usize,
) -> std::result::Result<String, String> {
    let url = reqwest::Url::parse(raw).map_err(|e| format!("{raw:?}: {e}"))?;
    let user_agent = format!("eclipse/{}", env!("CARGO_PKG_VERSION"));
    let ask = async {
        let mut resp = http::get(
            &url,
            timeout,
            reach,
            &[("Accept", accept), ("User-Agent", &user_agent)],
        )
        .await?;
        if !resp.status().is_success() {
            return Err(format!("{url} answered {}", resp.status()));
        }
        let mut body = Vec::new();
        while let Some(chunk) = resp.chunk().await.map_err(|e| e.to_string())? {
            body.extend_from_slice(&chunk);
            if body.len() > cap {
                // Truncating silently cut the JSON in half and handed the parser the pieces, so
                // the person saw a serde error instead of "this answer is not a release list"
                // (`#426`).
                return Err(format!(
                    "{url} answered more than {} KB, which is not a release list or a commit id; \
                     nothing was read",
                    cap / 1024
                ));
            }
        }
        Ok(String::from_utf8_lossy(&body).into_owned())
    };
    tokio::time::timeout(timeout, ask)
        .await
        .unwrap_or_else(|_| {
            Err(format!(
                "{url} did not answer within {} s",
                timeout.as_secs()
            ))
        })
}

/// Ask for the latest commit on the track's branch. One `GET` through [`http::get`], inside
/// [`CHECK_TIMEOUT`].
pub async fn fetch_latest(cfg: &UpdateConfig) -> std::result::Result<String, String> {
    let (raw, reach) = latest_question(cfg);
    let body = get_body(
        raw,
        reach,
        "application/vnd.github.sha",
        CHECK_TIMEOUT,
        MAX_ANSWER_BYTES,
    )
    .await?;
    parse_latest(&body).ok_or_else(|| format!("{raw} did not answer with a commit id"))
}

/// Ask for the newest release, through the same `GET`. `[update] releases` is the user's URL, so
/// it may be a host on their own network, exactly like `[update] remote`.
pub async fn fetch_release(cfg: &UpdateConfig) -> std::result::Result<Release, String> {
    let (raw, reach) = match cfg.releases.as_deref() {
        Some(r) => (r, Reach::Anywhere),
        None => (DEFAULT_RELEASES_URL, Reach::Public),
    };
    let body = get_body(
        raw,
        reach,
        "application/vnd.github+json",
        RELEASE_TIMEOUT,
        MAX_RELEASE_BYTES,
    )
    .await?;
    parse_release(&body).map_err(|e| format!("{raw}: {e}"))
}

/// Whether `latest` is something the install does not already contain.
///
/// Different ids are not enough: an install built from a commit *ahead* of the public branch
/// (a fork, unpushed work) would be told to "update" backwards. When the recorded checkout
/// still has the commit and it is an ancestor of what was installed, it is not news. Anything
/// this cannot establish — no checkout, no git, a commit the checkout has never seen — is news.
fn is_news(marker: &InstallMarker, installed: &str, latest: &str) -> bool {
    if latest == installed {
        return false;
    }
    let Some(workspace) = &marker.workspace else {
        return true;
    };
    let contains = std::process::Command::new("git")
        .arg("-C")
        .arg(workspace)
        .args(["merge-base", "--is-ancestor", latest, installed])
        .stdin(std::process::Stdio::null())
        .stdout(std::process::Stdio::null())
        .stderr(std::process::Stdio::null())
        .status()
        .is_ok_and(|s| s.success());
    !contains
}

/// What the marker says is installed, in the shape that channel compares. A marker that cannot
/// answer for its own channel has nothing to check against, and the notice stays silent.
#[derive(Debug, Clone, PartialEq, Eq)]
enum Installed {
    /// A source install: a commit id, compared with the branch's head.
    Commit(String),
    /// A release install: a version, compared with the newest tag.
    Version(Version),
}

impl Installed {
    fn of(marker: &InstallMarker) -> Option<Installed> {
        match marker.channel {
            Channel::Source => marker
                .commit
                .clone()
                .filter(|c| !c.is_empty())
                .map(Installed::Commit),
            Channel::Release => marker
                .version
                .as_deref()
                .and_then(Version::parse)
                .map(Installed::Version),
        }
    }
}

/// A newer version exists and the install has not taken it yet.
///
/// This is what a surface keeps on screen: a comparison, not an event. The same install stays
/// behind the same answer across any number of runs until `eclipse upgrade` rewrites
/// `install.json`, which is why it cannot be gated by the cache's `notified` field — that field
/// makes a line happen once, and the badge is a fact that lasts.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Behind {
    /// What the install has, in the shape its channel compares: a version, or a short commit.
    pub installed: String,
    /// The newest answer, the same shape: a tag as the release names it, or a short commit.
    pub latest: String,
}

impl Behind {
    /// `0.6.1` or `3f2a1c9`: the badge names the version, not the tag's `v` and not the whole
    /// forty-character commit id.
    pub fn shown_latest(&self) -> String {
        Version::parse(&self.latest)
            .map(|v| v.to_string())
            .unwrap_or_else(|| self.latest.clone())
    }

    /// The badge as one line, for a surface with one colour to give it: the terminal's plain
    /// REPL, and anything that logs.
    pub fn line(&self) -> String {
        format!("↑ {} available · eclipse upgrade", self.shown_latest())
    }
}

/// The marker and the cache compared: `Some` exactly while the installed thing is behind the
/// cached answer. One rule, so the badge, the REPL, the dashboard and the gateway cannot
/// disagree about what "behind" means.
pub fn behind(marker: &InstallMarker, cache: &UpdateCache) -> Option<Behind> {
    let latest = cache.latest.as_deref()?;
    match Installed::of(marker)? {
        Installed::Commit(commit) => is_news(marker, &commit, latest).then(|| Behind {
            installed: short(&commit).to_string(),
            latest: short(latest).to_string(),
        }),
        Installed::Version(version) => {
            // An answer that is not a version (an old commit id from a source install, a
            // captive portal) is not news rather than an error, exactly as the notice treats it.
            let newest = Version::parse(latest)?;
            (newest > version).then(|| Behind {
                installed: version.to_string(),
                latest: latest.trim().to_string(),
            })
        }
    }
}

/// How long an answer may stand before a surface that cannot refresh it stops repeating it. A
/// week is longer than either `[update] check` period, so only a machine that has stopped
/// asking reaches this.
pub const STALE_AFTER_SECS: u64 = 7 * 86_400;

/// What the dashboard renders: the cache's own numbers, with the comparison already made.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct Snapshot {
    /// The version (release install) or short commit (source install) the marker names.
    pub installed: Option<String>,
    /// The newest answer cached, in the same shape. `None` when nothing was ever cached.
    pub latest: Option<String>,
    /// Whether this install is behind *and* the answer is fresh enough to still mean it.
    pub behind: bool,
    /// Unix seconds of the last attempt, successful or not. `0` when never asked.
    pub checked_at: u64,
    pub channel: Option<Channel>,
}

/// Where a badge is read from, for a surface that asks more than once per process: the state
/// directory (the plain one, never a profile's — an install belongs to the machine user) and the
/// `[update]` section that decides whether there is anything to say. Reading it is two small
/// files, so a frame or a request may ask again rather than cache the answer in memory.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Watch {
    state: PathBuf,
    cfg: UpdateConfig,
}

impl Watch {
    /// The watch for a process's own environment. `None` when the user asked not to be told
    /// (`check = "off"`) or when there is no state directory to look in: both mean no badge.
    pub fn for_env(env: EnvFn, cfg: &UpdateConfig) -> Option<Watch> {
        if cfg.check == UpdateCheck::Off {
            return None;
        }
        Some(Watch {
            state: state_dir(env)?,
            cfg: cfg.clone(),
        })
    }

    /// The watch for a process that resolved its own state directory — the gateway, whose
    /// environment is the unit's, not a shell's.
    pub fn at(state: PathBuf, cfg: &UpdateConfig) -> Watch {
        Watch {
            state,
            cfg: cfg.clone(),
        }
    }

    /// The badge as the files stand now, or `None` when there is nothing to say.
    pub fn read(&self) -> Option<Behind> {
        if self.cfg.check == UpdateCheck::Off {
            return None;
        }
        let marker = InstallMarker::load(&self.state.join(MARKER_FILE))
            .ok()
            .flatten()?;
        let cache = UpdateCache::load(&self.state.join(CACHE_FILE));
        behind(&marker, &cache)
    }

    /// The same numbers, for a page: `checked_at` is kept so a stale claim can be recognised
    /// rather than shown, and the channel because the two channels upgrade differently.
    pub fn snapshot(&self, now_secs: u64) -> Snapshot {
        if self.cfg.check == UpdateCheck::Off {
            return Snapshot::default();
        }
        let marker = InstallMarker::load(&self.state.join(MARKER_FILE))
            .ok()
            .flatten();
        let cache = UpdateCache::load(&self.state.join(CACHE_FILE));
        let behind = marker.as_ref().and_then(|m| behind(m, &cache));
        let fresh = now_secs.saturating_sub(cache.checked_at) <= STALE_AFTER_SECS;
        Snapshot {
            installed: behind
                .as_ref()
                .map(|b| b.installed.clone())
                .or_else(|| marker.as_ref().and_then(installed_text)),
            latest: behind
                .as_ref()
                .map(|b| b.latest.clone())
                .or_else(|| cache.latest.clone()),
            behind: behind.is_some() && fresh,
            checked_at: cache.checked_at,
            channel: marker.as_ref().map(|m| m.channel),
        }
    }
}

/// What the marker says it has, as a reader would write it: the version a release install
/// reports, or the short commit a source install was built from.
fn installed_text(marker: &InstallMarker) -> Option<String> {
    match Installed::of(marker)? {
        Installed::Commit(commit) => Some(short(&commit).to_string()),
        Installed::Version(version) => Some(version.to_string()),
    }
}

/// What one refresh did, for a caller that logs or tests it. `Behind` carries the badge, so a
/// caller that only renders does not have to ask the disk again.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Outcome {
    /// Nothing was asked: `check = "off"`, no install marker, or the answer is still inside
    /// the period and the install is current.
    NotDue,
    Current,
    Behind(Behind),
    Failed(String),
}

/// Ask the repository, if the cache says it is time, and leave the answer where every reader
/// looks. This is what a long-lived process runs on its schedule: the CLI's per-run check and
/// the gateway's tick write the same `update.json`, so one of them answering spares the other
/// the request.
///
/// Nothing here installs anything: a version change is a decision, and a background timer is
/// not the place to make it.
pub async fn refresh(state: &Path, cfg: &UpdateConfig) -> Outcome {
    if cfg.check == UpdateCheck::Off {
        return Outcome::NotDue;
    }
    let Ok(Some(marker)) = InstallMarker::load(&state.join(MARKER_FILE)) else {
        return Outcome::NotDue;
    };
    let Some(installed) = Installed::of(&marker) else {
        return Outcome::NotDue;
    };
    let cache_path = state.join(CACHE_FILE);
    let mut cache = UpdateCache::load(&cache_path);
    let now = crate::session::now_ms() / 1000;
    if !cache.is_due(cfg.check, now) {
        return match behind(&marker, &cache) {
            Some(b) => Outcome::Behind(b),
            None => Outcome::NotDue,
        };
    }
    // The attempt is recorded before the question. A server that is down must not be asked on
    // every tick, and a process killed mid-request must not leave the next one asking either.
    cache.checked_at = now;
    cache.save(&cache_path);
    match ask_and_cache(state, cfg, &installed).await {
        Ok(_) => match behind(&marker, &UpdateCache::load(&cache_path)) {
            Some(b) => Outcome::Behind(b),
            None => Outcome::Current,
        },
        Err(why) => Outcome::Failed(why),
    }
}

/// The one question this module asks on a schedule, answered into the cache. Returns the
/// answer it wrote, which is what the caller's log line names.
async fn ask_and_cache(
    state: &Path,
    cfg: &UpdateConfig,
    installed: &Installed,
) -> std::result::Result<String, String> {
    let latest = match installed {
        Installed::Version(_) => fetch_release(cfg).await.map(|release| release.tag),
        Installed::Commit(_) => fetch_latest(cfg).await,
    }?;
    // Re-read before writing: another process may have recorded an attempt meanwhile, and its
    // `checked_at` is the one that keeps the next run quiet.
    let path = state.join(CACHE_FILE);
    let mut cache = UpdateCache::load(&path);
    cache.latest = Some(latest.clone());
    cache.save(&path);
    Ok(latest)
}

/// The marker's `installed_at`: RFC 3339 in UTC, the same shape `install.sh` writes with
/// `date -u`, so the two cannot disagree about what a timestamp looks like.
pub fn rfc3339_utc(ms: u64) -> String {
    let secs = ms / 1000;
    let (y, m, d) = crate::cron::civil_from_days((secs / 86_400) as i64);
    let rem = secs % 86_400;
    format!(
        "{y:04}-{m:02}-{d:02}T{:02}:{:02}:{:02}Z",
        rem / 3600,
        (rem % 3600) / 60,
        rem % 60
    )
}

fn short(id: &str) -> &str {
    id.get(..7).unwrap_or(id)
}

/// What a front door (`run`, the interactive interface) does about the notice: the line to say
/// once, if any, the badge, and the refresh that may still be in flight.
#[derive(Default)]
pub struct Check {
    /// The one-line notice, already marked as shown in the cache.
    pub notice: Option<String>,
    /// The badge as the disk stood when the run started. A surface that repaints reads its
    /// [`Watch`] again instead of this, so an answer that lands mid-run still shows up.
    pub badge: Option<Behind>,
    refresh: Option<tokio::task::JoinHandle<()>>,
}

impl Check {
    /// Never started anything: `[update] check = "off"`, no install marker, or nothing due.
    pub fn idle() -> Check {
        Check::default()
    }

    /// Start the notice for this run. Never fails and never waits: the line printed comes from
    /// what an earlier run cached, and a refresh, if one is due, runs in the background.
    /// Needs a tokio runtime.
    pub fn start(env: EnvFn, cfg: &UpdateConfig) -> Check {
        if cfg.check == UpdateCheck::Off {
            return Check::idle();
        }
        let Some(state) = state_dir(env) else {
            return Check::idle();
        };
        let Ok(Some(marker)) = InstallMarker::load(&state.join(MARKER_FILE)) else {
            return Check::idle();
        };
        let Some(installed) = Installed::of(&marker) else {
            return Check::idle();
        };
        let cache_path = state.join(CACHE_FILE);
        let mut cache = UpdateCache::load(&cache_path);

        // The badge is the comparison; the notice is that comparison being said for the first
        // time, which is what `notified` still keeps to one line per answer. The badge itself
        // is not gated by it: an install that stays behind stays behind across every run.
        let badge = behind(&marker, &cache);
        let mut notice = None;
        if let Some(behind) = &badge {
            if cache.latest.as_deref() != cache.notified.as_deref() {
                notice = Some(format!(
                    "a newer eclipse is available ({}, installed {}): run `eclipse upgrade` \
                     \u{2014} this notice is `[update] check`, set it to \"off\" to stop it",
                    behind.latest, behind.installed
                ));
                cache.notified = cache.latest.clone();
            }
        }

        let now = crate::session::now_ms() / 1000;
        let due = cache.is_due(cfg.check, now);
        if due {
            cache.checked_at = now;
        }
        if notice.is_some() || due {
            cache.save(&cache_path);
        }

        let refresh = due.then(|| {
            let cfg = cfg.clone();
            let state = state.clone();
            tokio::spawn(async move {
                let _ = ask_and_cache(&state, &cfg, &installed).await;
            })
        });
        Check {
            notice,
            badge,
            refresh,
        }
    }

    /// Give a refresh still in flight its chance to land before the process exits. It was
    /// started with the run, so after any real run this returns at once; the worst case is the
    /// deadline the request itself is limited to.
    pub async fn finish(self) {
        if let Some(handle) = self.refresh {
            let _ = tokio::time::timeout(RELEASE_TIMEOUT, handle).await;
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::io::{Read, Write};
    use std::sync::atomic::{AtomicUsize, Ordering};
    use std::sync::Arc;

    const OLD: &str = "1111111111111111111111111111111111111111";
    const NEW: &str = "2222222222222222222222222222222222222222";

    /// A loopback server that answers every request with `body` and counts them.
    fn serve(body: &'static str) -> (String, Arc<AtomicUsize>) {
        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
        let url = format!("http://{}/latest", listener.local_addr().unwrap());
        let hits = Arc::new(AtomicUsize::new(0));
        let counted = hits.clone();
        std::thread::spawn(move || {
            while let Ok((mut s, _)) = listener.accept() {
                counted.fetch_add(1, Ordering::SeqCst);
                let mut buf = [0u8; 2048];
                let _ = s.read(&mut buf);
                let _ = write!(
                    s,
                    "HTTP/1.1 200 OK\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{body}",
                    body.len()
                );
            }
        });
        (url, hits)
    }

    /// A URL nothing listens on.
    fn dead_url() -> String {
        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
        let url = format!("http://{}/latest", listener.local_addr().unwrap());
        drop(listener);
        url
    }

    /// A state directory holding a marker for an install built from `OLD`.
    fn installed(remote: &str, check: UpdateCheck) -> (tempfile::TempDir, UpdateConfig) {
        let home = tempfile::tempdir().unwrap();
        let state = home.path().join(".eclipse/state");
        std::fs::create_dir_all(&state).unwrap();
        std::fs::write(
            state.join(MARKER_FILE),
            format!(
                r#"{{"channel":"source","prefix":"/x","commit":"{OLD}","installed_at":"2026-01-01T00:00:00Z"}}"#
            ),
        )
        .unwrap();
        let cfg = UpdateConfig {
            check,
            track: Track::Release,
            remote: Some(remote.to_string()),
            releases: None,
        };
        (home, cfg)
    }

    fn env_of(home: &Path) -> impl Fn(&str) -> Option<String> {
        let home = home.to_string_lossy().into_owned();
        move |k| (k == "HOME").then(|| home.clone())
    }

    async fn one_run(home: &Path, cfg: &UpdateConfig) -> Option<String> {
        let env = env_of(home);
        let check = Check::start(&env, cfg);
        let notice = check.notice.clone();
        check.finish().await;
        notice
    }

    #[tokio::test]
    async fn the_latest_commit_is_asked_once_per_period_and_the_notice_is_said_once() {
        let (url, hits) = serve(NEW);
        let (home, cfg) = installed(&url, UpdateCheck::Daily);

        // The first run has nothing cached to say, but it asks.
        assert_eq!(one_run(home.path(), &cfg).await, None);
        assert_eq!(hits.load(Ordering::SeqCst), 1);

        // The second run says it, from the cache, without asking again.
        let line = one_run(home.path(), &cfg).await.expect("a notice");
        assert!(
            line.contains("2222222") && line.contains("eclipse upgrade"),
            "{line}"
        );
        assert!(
            line.contains("off"),
            "it says how to turn itself off: {line}"
        );
        assert_eq!(
            hits.load(Ordering::SeqCst),
            1,
            "one request across two runs"
        );

        // And only once.
        assert_eq!(one_run(home.path(), &cfg).await, None);
        assert_eq!(hits.load(Ordering::SeqCst), 1);
    }

    #[tokio::test]
    async fn a_server_that_is_down_is_silent_and_is_not_asked_again_within_the_period() {
        let (home, cfg) = installed(&dead_url(), UpdateCheck::Daily);
        assert_eq!(one_run(home.path(), &cfg).await, None);
        let cache = UpdateCache::load(&home.path().join(".eclipse/state").join(CACHE_FILE));
        assert!(cache.checked_at > 0, "the attempt is recorded");
        assert_eq!(cache.latest, None);
        assert!(!cache.is_due(UpdateCheck::Daily, cache.checked_at + 60));
        assert_eq!(one_run(home.path(), &cfg).await, None);
    }

    #[tokio::test]
    async fn an_answer_that_is_not_a_commit_id_is_never_cached_as_one() {
        let (url, hits) = serve("<html>captive portal</html>");
        let (home, cfg) = installed(&url, UpdateCheck::Daily);
        assert_eq!(one_run(home.path(), &cfg).await, None);
        assert_eq!(hits.load(Ordering::SeqCst), 1);
        let cache = UpdateCache::load(&home.path().join(".eclipse/state").join(CACHE_FILE));
        assert_eq!(cache.latest, None);
    }

    #[tokio::test]
    async fn check_off_makes_no_request_and_writes_nothing() {
        let (url, hits) = serve(NEW);
        let (home, cfg) = installed(&url, UpdateCheck::Off);
        assert_eq!(one_run(home.path(), &cfg).await, None);
        assert_eq!(hits.load(Ordering::SeqCst), 0);
        assert!(!home.path().join(".eclipse/state").join(CACHE_FILE).exists());
    }

    #[tokio::test]
    async fn a_run_with_no_install_marker_makes_no_request() {
        let (url, hits) = serve(NEW);
        let home = tempfile::tempdir().unwrap();
        let cfg = UpdateConfig {
            check: UpdateCheck::Daily,
            track: Track::Release,
            remote: Some(url),
            releases: None,
        };
        assert_eq!(one_run(home.path(), &cfg).await, None);
        assert_eq!(
            hits.load(Ordering::SeqCst),
            0,
            "nothing to compare with, nothing asked"
        );
    }

    #[test]
    fn a_commit_id_is_read_from_a_bare_body_or_a_json_sha_and_nothing_else() {
        assert_eq!(parse_latest(&format!("{NEW}\n")).as_deref(), Some(NEW));
        assert_eq!(
            parse_latest(&format!(
                r#"{{"sha":"{}","commit":{{}}}}"#,
                NEW.to_uppercase()
            ))
            .as_deref(),
            Some(NEW)
        );
        for bad in ["", "main", "abc123", r#"{"sha":"nope"}"#, "<html></html>"] {
            assert_eq!(parse_latest(bad), None, "{bad:?}");
        }
    }

    /// The track names a branch, and the question follows it — unless the person wrote a URL,
    /// which is the escape hatch a track must not quietly reroute.
    #[test]
    fn the_commit_question_follows_the_tracks_branch_unless_a_remote_was_set() {
        let asked = |track, remote: Option<&str>| {
            let cfg = UpdateConfig {
                check: UpdateCheck::Daily,
                track,
                remote: remote.map(str::to_string),
                releases: None,
            };
            latest_question(&cfg).0.to_string()
        };
        assert_eq!(asked(Track::Release, None), DEFAULT_LATEST_URL);
        assert_eq!(
            asked(Track::Develop, None),
            DEVELOP_LATEST_URL,
            "a develop checkout is asked about develop, never about main"
        );
        assert!(DEVELOP_LATEST_URL.ends_with("/commits/develop"));
        for track in [Track::Release, Track::Develop] {
            assert_eq!(
                asked(track, Some("http://mirror/latest")),
                "http://mirror/latest",
                "an explicit remote wins on either track"
            );
        }
    }

    #[test]
    fn a_marker_that_is_missing_is_none_and_one_that_is_broken_names_its_file() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join(MARKER_FILE);
        assert_eq!(InstallMarker::load(&path).unwrap(), None);
        std::fs::write(
            &path,
            r#"{"channel":"carrier-pigeon","prefix":"/x","installed_at":"t"}"#,
        )
        .unwrap();
        let err = InstallMarker::load(&path).unwrap_err().to_string();
        assert!(
            err.contains("install.json") && err.contains("carrier-pigeon"),
            "{err}"
        );
    }

    #[test]
    fn a_marker_from_a_tarball_install_has_no_commit_and_no_checkout() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join(MARKER_FILE);
        std::fs::write(
            &path,
            r#"{"channel":"source","prefix":"/p","workspace":null,"commit":null,"installed_at":"2026-01-01T00:00:00Z"}"#,
        )
        .unwrap();
        let m = InstallMarker::load(&path).unwrap().unwrap();
        assert_eq!((m.commit, m.workspace), (None, None));
    }

    fn git(dir: &Path, args: &[&str]) -> String {
        let out = std::process::Command::new("git")
            .arg("-C")
            .arg(dir)
            .args(["-c", "user.name=t", "-c", "user.email=t@t"])
            .args(args)
            .output()
            .unwrap();
        assert!(out.status.success(), "git {args:?}: {out:?}");
        String::from_utf8_lossy(&out.stdout).trim().to_string()
    }

    #[test]
    fn a_release_version_is_three_numbers_and_orders_by_them() {
        assert_eq!(
            Version::parse("v0.2.1"),
            Some(Version {
                major: 0,
                minor: 2,
                patch: 1
            })
        );
        assert_eq!(Version::parse(" 0.10.0 ").unwrap().to_string(), "0.10.0");
        assert!(Version::parse("v0.10.0") > Version::parse("v0.9.9"));
        assert!(Version::parse("v1.0.0") > Version::parse("v0.99.99"));
        for bad in [
            "",
            "v",
            "1",
            "1.2",
            "1.2.3.4",
            "v1.two.3",
            "main",
            "v0.2.1-rc1.x",
        ] {
            assert_eq!(Version::parse(bad), None, "{bad:?}");
        }
    }

    #[test]
    fn a_release_answer_names_the_linux_tarball_and_its_sums_or_says_what_it_carries() {
        let body = format!(
            r#"{{
                "tag_name": "v0.3.0",
                "html_url": "https://example.invalid/releases/v0.3.0",
                "assets": [
                    {{"name": "eclipse-v0.3.0-aarch64-apple-darwin.tar.gz", "browser_download_url": "https://x/mac"}},
                    {{"name": "eclipse-v0.3.0-x86_64-unknown-linux-gnu.tar.gz", "browser_download_url": "https://x/linux"}},
                    {{"name": "{SUMS_NAME}", "browser_download_url": "https://x/sums"}}
                ]
            }}"#
        );
        let release = parse_release(&body).expect("a release");
        assert_eq!(release.version.to_string(), "0.3.0");
        assert_eq!(release.tarball_url, "https://x/linux");
        assert_eq!(release.sums_url, "https://x/sums");
        assert_eq!(
            release.page.as_deref(),
            Some("https://example.invalid/releases/v0.3.0")
        );

        // No Linux asset: the refusal lists what the release does carry, which is what makes it
        // actionable rather than a bare "not found".
        let missing = parse_release(
            r#"{"tag_name":"v0.3.0","assets":[{"name":"eclipse-v0.3.0-aarch64-apple-darwin.tar.gz","browser_download_url":"https://x/mac"}]}"#,
        )
        .unwrap_err();
        assert!(
            missing.contains("no") && missing.contains("darwin"),
            "{missing}"
        );

        // A tag that is not a version at all is refused by name, not parsed into nonsense.
        let bad_tag = parse_release(r#"{"tag_name":"nightly","assets":[]}"#).unwrap_err();
        assert!(bad_tag.contains("nightly"), "{bad_tag}");
    }

    /// A state directory holding a release marker, and a config whose release question points at
    /// `url`.
    fn installed_release(version: &str, url: &str) -> (tempfile::TempDir, UpdateConfig) {
        let home = tempfile::tempdir().unwrap();
        let state = home.path().join(".eclipse/state");
        std::fs::create_dir_all(&state).unwrap();
        std::fs::write(
            state.join(MARKER_FILE),
            format!(
                r#"{{"channel":"release","prefix":"/x","workspace":null,"commit":null,"installed_at":"2026-01-01T00:00:00Z","build":"release","version":"{version}"}}"#
            ),
        )
        .unwrap();
        let cfg = UpdateConfig {
            check: UpdateCheck::Daily,
            track: Track::Release,
            remote: None,
            releases: Some(url.to_string()),
        };
        (home, cfg)
    }

    #[tokio::test]
    async fn a_release_install_is_told_about_a_newer_tag_by_version_and_only_once() {
        let body: &'static str = Box::leak(
            format!(
                r#"{{"tag_name":"v0.3.0","assets":[{{"name":"eclipse-v0.3.0{TARBALL_SUFFIX}","browser_download_url":"https://x/linux"}},{{"name":"{SUMS_NAME}","browser_download_url":"https://x/sums"}}]}}"#
            )
            .into_boxed_str(),
        );
        let (url, hits) = serve(body);
        let (home, cfg) = installed_release("0.2.0", &url);

        // The first run asks; the notice comes from the second run's cache.
        assert_eq!(one_run(home.path(), &cfg).await, None);
        assert_eq!(hits.load(Ordering::SeqCst), 1);
        let line = one_run(home.path(), &cfg).await.expect("a notice");
        assert!(
            line.contains("v0.3.0") && line.contains("0.2.0") && line.contains("eclipse upgrade"),
            "{line}"
        );
        assert_eq!(one_run(home.path(), &cfg).await, None, "said once");
        assert_eq!(hits.load(Ordering::SeqCst), 1);
    }

    #[tokio::test]
    async fn a_release_install_on_the_newest_tag_is_silent() {
        let body: &'static str = Box::leak(
            format!(
                r#"{{"tag_name":"v0.2.0","assets":[{{"name":"eclipse-v0.2.0{TARBALL_SUFFIX}","browser_download_url":"https://x/linux"}},{{"name":"{SUMS_NAME}","browser_download_url":"https://x/sums"}}]}}"#
            )
            .into_boxed_str(),
        );
        let (url, _hits) = serve(body);
        let (home, cfg) = installed_release("0.2.0", &url);
        assert_eq!(one_run(home.path(), &cfg).await, None);
        assert_eq!(one_run(home.path(), &cfg).await, None, "never a notice");
    }

    #[tokio::test]
    async fn a_release_marker_with_no_version_asks_nothing() {
        let (url, hits) = serve("{}");
        let home = tempfile::tempdir().unwrap();
        let state = home.path().join(".eclipse/state");
        std::fs::create_dir_all(&state).unwrap();
        std::fs::write(
            state.join(MARKER_FILE),
            r#"{"channel":"release","prefix":"/x","installed_at":"t"}"#,
        )
        .unwrap();
        let cfg = UpdateConfig {
            check: UpdateCheck::Daily,
            track: Track::Release,
            remote: None,
            releases: Some(url),
        };
        assert_eq!(one_run(home.path(), &cfg).await, None);
        assert_eq!(hits.load(Ordering::SeqCst), 0);
    }

    #[test]
    fn a_commit_the_install_already_contains_is_not_news_and_one_it_has_never_seen_is() {
        let repo = tempfile::tempdir().unwrap();
        git(repo.path(), &["init", "-q"]);
        git(repo.path(), &["commit", "-q", "--allow-empty", "-m", "one"]);
        let first = git(repo.path(), &["rev-parse", "HEAD"]);
        git(repo.path(), &["commit", "-q", "--allow-empty", "-m", "two"]);
        let second = git(repo.path(), &["rev-parse", "HEAD"]);
        let marker = InstallMarker {
            channel: Channel::Source,
            prefix: "/x".into(),
            workspace: Some(repo.path().to_path_buf()),
            commit: Some(second.clone()),
            installed_at: "t".into(),
            build: None,
            version: None,
        };
        assert!(!is_news(&marker, &second, &second));
        assert!(
            !is_news(&marker, &second, &first),
            "an older commit is not an update"
        );
        assert!(is_news(&marker, &first, &second), "a newer one is");
        assert!(
            is_news(&marker, &second, NEW),
            "so is one this checkout has never seen"
        );
    }

    /// A release answer for `tag`, as a static body a loopback server can hand back.
    fn release_body(tag: &str) -> &'static str {
        Box::leak(
            format!(
                r#"{{"tag_name":"{tag}","assets":[{{"name":"eclipse-{tag}{TARBALL_SUFFIX}","browser_download_url":"https://x/linux"}},{{"name":"{SUMS_NAME}","browser_download_url":"https://x/sums"}}]}}"#
            )
            .into_boxed_str(),
        )
    }

    /// The same run `one_run` makes, keeping the badge as well as the notice.
    async fn one_run_check(home: &Path, cfg: &UpdateConfig) -> (Option<String>, Option<Behind>) {
        let env = env_of(home);
        let check = Check::start(&env, cfg);
        let seen = (check.notice.clone(), check.badge.clone());
        check.finish().await;
        seen
    }

    fn state_of(home: &Path) -> PathBuf {
        home.join(".eclipse/state")
    }

    /// The file `eclipse upgrade` rewrites, for the test that moves an install forward.
    fn rewrite_marker_version(home: &Path, version: &str) {
        std::fs::write(
            state_of(home).join(MARKER_FILE),
            format!(
                r#"{{"channel":"release","prefix":"/x","installed_at":"2026-01-01T00:00:00Z","version":"{version}"}}"#
            ),
        )
        .unwrap();
    }

    fn write_cache(home: &Path, latest: &str, checked_at: u64) {
        let cache = UpdateCache {
            checked_at,
            latest: Some(latest.to_string()),
            notified: None,
        };
        cache.save(&state_of(home).join(CACHE_FILE));
    }

    fn now_secs() -> u64 {
        crate::session::now_ms() / 1000
    }

    /// The issue's headline: the notice is a one-shot, the badge is not. An install that stays
    /// behind says so on every run, and says it without asking again.
    #[tokio::test]
    async fn the_badge_lasts_across_runs_while_the_notice_is_only_said_once() {
        let (url, hits) = serve(release_body("v0.3.0"));
        let (home, cfg) = installed_release("0.2.0", &url);

        // The first run asks, and there is nothing cached to badge yet.
        assert_eq!(one_run_check(home.path(), &cfg).await, (None, None));
        assert_eq!(hits.load(Ordering::SeqCst), 1);

        // The second run says it, and shows it.
        let (notice, badge) = one_run_check(home.path(), &cfg).await;
        assert!(
            notice.expect("a notice").contains("v0.3.0"),
            "the notice still names the tag"
        );
        let badge = badge.expect("a badge");
        assert_eq!(badge.installed, "0.2.0");
        assert_eq!(
            badge.line(),
            "↑ 0.3.0 available · eclipse upgrade",
            "one version, without the tag's v"
        );

        // The third run is the whole point: the notice is spent, the badge is not.
        let (notice, badge) = one_run_check(home.path(), &cfg).await;
        assert_eq!(notice, None, "a notice happens once per answer");
        assert!(
            badge.is_some(),
            "a badge lasts as long as the install is behind"
        );
        assert_eq!(hits.load(Ordering::SeqCst), 1, "neither run asked again");
    }

    /// And it goes when the install moves, from the marker alone: no timer, no acknowledgement.
    #[tokio::test]
    async fn the_badge_clears_when_the_install_reaches_the_new_version() {
        let (url, _hits) = serve(release_body("v0.3.0"));
        let (home, cfg) = installed_release("0.2.0", &url);
        assert_eq!(one_run_check(home.path(), &cfg).await, (None, None));
        assert!(one_run_check(home.path(), &cfg).await.1.is_some());

        rewrite_marker_version(home.path(), "0.3.0");
        let env = env_of(home.path());
        let watch = Watch::for_env(&env, &cfg).expect("a watch");
        assert_eq!(watch.read(), None, "the upgrade is what clears it");
    }

    /// A source install has no version, so the badge names the short commit it was built from.
    #[test]
    fn a_source_install_badges_the_short_commit_it_has_never_seen() {
        let marker = InstallMarker {
            channel: Channel::Source,
            prefix: "/x".into(),
            workspace: None,
            commit: Some(OLD.into()),
            installed_at: "t".into(),
            build: None,
            version: None,
        };
        let cache = UpdateCache {
            checked_at: 1,
            latest: Some(NEW.into()),
            notified: Some(NEW.into()),
        };
        let badge = behind(&marker, &cache).expect("a badge");
        assert_eq!(badge.installed, "1111111");
        assert_eq!(badge.line(), "↑ 2222222 available · eclipse upgrade");
    }

    /// `check = "off"` is not "do not ask" — it is "do not tell me", so a cached answer from
    /// before the switch cannot bring the badge back on either surface.
    #[tokio::test]
    async fn check_off_produces_no_badge_even_from_a_cached_answer() {
        let (home, mut cfg) = installed_release("0.2.0", "http://127.0.0.1:1/latest");
        write_cache(home.path(), "v0.3.0", now_secs());
        cfg.check = UpdateCheck::Off;

        let env = env_of(home.path());
        assert!(Watch::for_env(&env, &cfg).is_none(), "nothing to watch");
        assert_eq!(Check::start(&env, &cfg).badge, None);

        // The dashboard asks the same question through a state directory it already resolved.
        let snapshot = Watch::at(state_of(home.path()), &cfg).snapshot(now_secs());
        assert!(
            !snapshot.behind,
            "the answer is there and must not be shown"
        );
        assert_eq!(snapshot.latest, None);
    }

    /// A gateway that has stopped asking must stop claiming: a week-old answer is a stale
    /// answer, and the page shows nothing rather than a version that may long since be gone.
    #[test]
    fn a_snapshot_stops_claiming_an_answer_older_than_a_week() {
        let (home, cfg) = installed_release("0.2.0", "http://127.0.0.1:1/latest");
        let now = now_secs();
        write_cache(home.path(), "v0.3.0", now - STALE_AFTER_SECS - 60);

        let snapshot = Watch::at(state_of(home.path()), &cfg).snapshot(now);
        assert!(!snapshot.behind, "eight days old is not a claim to make");
        assert_eq!(snapshot.installed.as_deref(), Some("0.2.0"));
        assert_eq!(
            snapshot.latest.as_deref(),
            Some("v0.3.0"),
            "the number is still reported, it is the claim that is withheld"
        );
        assert_eq!(snapshot.channel, Some(Channel::Release));

        // Inside the week, the same cache is the badge the CLI would show.
        write_cache(home.path(), "v0.3.0", now - 3600);
        let fresh = Watch::at(state_of(home.path()), &cfg).snapshot(now);
        assert!(fresh.behind);
        assert_eq!(fresh.checked_at, now - 3600);
    }

    /// The gateway's tick and the CLI's run share one cache: whoever asks first spares the
    /// other the request, which is what keeps three dashboard tabs from hammering GitHub.
    #[tokio::test]
    async fn a_scheduled_refresh_writes_the_cache_and_asks_once_a_period() {
        let (url, hits) = serve(release_body("v0.3.0"));
        let (home, cfg) = installed_release("0.2.0", &url);
        let state = state_of(home.path());

        match refresh(&state, &cfg).await {
            Outcome::Behind(badge) => assert_eq!(badge.latest, "v0.3.0"),
            other => panic!("expected a badge, got {other:?}"),
        }
        assert_eq!(hits.load(Ordering::SeqCst), 1);
        let cache = UpdateCache::load(&state.join(CACHE_FILE));
        assert!(cache.checked_at > 0, "the attempt is recorded");
        assert_eq!(cache.latest.as_deref(), Some("v0.3.0"));

        // Inside the period: the answer is read, nothing is asked.
        assert!(matches!(refresh(&state, &cfg).await, Outcome::Behind(_)));
        assert_eq!(hits.load(Ordering::SeqCst), 1, "one request per period");
        assert_eq!(
            Watch::at(state.clone(), &cfg).read().map(|b| b.latest),
            Some("v0.3.0".to_string()),
            "and the CLI's reader sees exactly what the gateway wrote"
        );
    }

    /// A check that cannot reach the repository says why, and still counts as the period's
    /// attempt so a downed server is not asked on every tick.
    #[tokio::test]
    async fn a_refresh_that_fails_reports_it_and_records_the_attempt() {
        let (home, cfg) = installed_release("0.2.0", &dead_url());
        let state = state_of(home.path());
        match refresh(&state, &cfg).await {
            Outcome::Failed(why) => assert!(!why.is_empty(), "{why}"),
            other => panic!("expected a failure, got {other:?}"),
        }
        let cache = UpdateCache::load(&state.join(CACHE_FILE));
        assert!(cache.checked_at > 0, "a failure is still an attempt");
        assert_eq!(cache.latest, None);
        assert!(
            matches!(refresh(&state, &cfg).await, Outcome::NotDue),
            "and the next tick inside the period asks nothing"
        );
    }
}