Skip to content

SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.

51.6 KB
Raw Blame
use super::*;
use serde_json::json;
use std::collections::BTreeMap;

#[test]
fn versions_compare_as_semver() {
    assert!(is_newer("v0.10.0", "0.9.0"));
    assert!(is_newer("v0.10.0", "0.9.12"), "0.10 is after 0.9.12, not before it as text would sort");
    assert!(is_newer("v1.0.0", "0.10.0"));
    assert!(!is_newer("v0.10.0", "0.10.0"));
    assert!(!is_newer("v0.9.0", "0.10.0"));
    // A release candidate is older than its release; the release is offered to it.
    assert!(is_newer("v0.11.0", "0.11.0-rc.2"));
    // A prerelease is never offered (releases/latest never returns one anyway).
    assert!(!is_newer("v0.12.0-rc.1", "0.11.0"));
    assert!(!is_newer("garbage", "0.9.0"));
    assert!(!is_newer("v0.10.0", "not a version"));
}

#[test]
fn nightlies_count_as_the_release_they_follow() {
    // Built from main after 0.10.0: not nagged about 0.10.0 itself.
    assert!(!is_newer("v0.10.0", "0.10.0-nightly.20261015.37.1"));
    assert!(!is_newer("v0.9.0", "0.10.0-nightly.20261015.37.1"));
    // A newer stable release is offered.
    assert!(is_newer("v0.11.0", "0.10.0-nightly.20261015.37.1"));
    assert!(is_newer("v0.10.0", "0.9.0-nightly.20261014.36.1"));
}

fn probe(os: &str, release: bool, env: &[(&str, &str)], exe: &str, files: &[&str]) -> InstallKind {
    let env: BTreeMap<String, String> = env.iter().map(|(k, v)| (k.to_string(), v.to_string())).collect();
    let files: Vec<PathBuf> = files.iter().map(PathBuf::from).collect();
    let get = |k: &str| env.get(k).cloned();
    let exists = |p: &Path| files.iter().any(|f| f == p);
    detect(&Probe { os, release_build: release, env: &get, exe: Some(PathBuf::from(exe)), exists: &exists, msi_dir: None })
}

#[test]
fn install_kinds_are_told_apart() {
    let home = "/home/me/Apps/solidcraft";
    assert_eq!(probe("linux", false, &[("APPIMAGE", "/x.AppImage")], home, &[]), InstallKind::Dev, "dev builds never check");
    assert_eq!(probe("linux", true, &[("FLATPAK_ID", APP_ID)], "/app/bin/solidcraft", &[]), InstallKind::Flatpak(APP_ID.into()));
    let snap = |rev: &str| {
        probe(
            "linux",
            true,
            &[("SNAP", "/snap/solidcraft/12"), ("SNAP_NAME", "solidcraft"), ("SNAP_REVISION", rev)],
            "/snap/solidcraft/12/usr/bin/solidcraft",
            &[],
        )
    };
    assert_eq!(snap("12"), InstallKind::Snap { store: true });
    assert_eq!(snap("x3"), InstallKind::Snap { store: false }, "installed from a file with --dangerous");
    assert_eq!(
        probe("linux", true, &[("APPIMAGE", "/home/me/SolidCraft.AppImage")], "/tmp/.mount_SolidXYZ/usr/bin/solidcraft", &[]),
        InstallKind::AppImage("/home/me/SolidCraft.AppImage".into())
    );
    // An empty variable doesn't count.
    assert_eq!(probe("linux", true, &[("APPIMAGE", "")], "/opt/sc/bin/solidcraft", &[]), InstallKind::LinuxTarball);
    assert_eq!(probe("linux", true, &[], "/usr/bin/solidcraft", &["/var/lib/dpkg/info/solidcraft.list", "/var/lib/rpm"]), InstallKind::Deb);
    assert_eq!(probe("linux", true, &[], "/usr/bin/solidcraft", &["/var/lib/rpm"]), InstallKind::Rpm);
    assert_eq!(probe("linux", true, &[], "/usr/bin/solidcraft", &["/usr/lib/sysimage/rpm"]), InstallKind::Rpm);
    assert_eq!(probe("linux", true, &[], "/usr/bin/solidcraft", &[]), InstallKind::Other);
    assert_eq!(probe("linux", true, &[], home, &[]), InstallKind::LinuxTarball);

    let pf = [("ProgramFiles", "C:\\Program Files"), ("ProgramFiles(x86)", "C:\\Program Files (x86)")];
    assert_eq!(probe("windows", true, &pf, "C:\\Program Files\\SolidCraft\\solidcraft.exe", &[]), InstallKind::WindowsMsi);
    assert_eq!(probe("windows", true, &pf, "c:\\program files\\SolidCraft\\solidcraft.exe", &[]), InstallKind::WindowsMsi, "case-insensitive");
    // "C:\Program Files Extra" is not under "C:\Program Files".
    assert_eq!(probe("windows", true, &pf, "C:\\Program Files Extra\\solidcraft.exe", &[]), InstallKind::WindowsExe);
    let portable = "C:\\Users\\me\\solidcraft-0.10.0-windows-x64-portable\\solidcraft.exe";
    let cli = "C:\\Users\\me\\solidcraft-0.10.0-windows-x64-portable\\solidcraft-cli.exe";
    // Path::parent splits on `\` only on Windows; this test describes the layout either way.
    if cfg!(windows) {
        assert_eq!(probe("windows", true, &pf, portable, &[cli]), InstallKind::WindowsPortable);
    }
    assert_eq!(probe("windows", true, &pf, "C:\\Users\\me\\Downloads\\SolidCraft-0.10.0-windows-x64.exe", &[]), InstallKind::WindowsExe);

    assert_eq!(
        probe("macos", true, &[], "/Applications/SolidCraft.app/Contents/MacOS/solidcraft", &[]),
        InstallKind::MacApp("/Applications/SolidCraft.app".into())
    );
    assert_eq!(probe("macos", true, &[], "/usr/local/bin/solidcraft", &[]), InstallKind::Other);
    assert_eq!(probe("macos", false, &[], "/Applications/SolidCraft.app/Contents/MacOS/solidcraft", &[]), InstallKind::Dev);
    assert_eq!(probe("freebsd", true, &[], "/usr/local/bin/solidcraft", &[]), InstallKind::Other);
    assert!(!InstallKind::Dev.checks() && !InstallKind::Web.checks() && InstallKind::Snap { store: true }.checks());
    assert!(!InstallKind::Flatpak(APP_ID.into()).checks(), "the Flatpak has no network permission; Flatpak updates it");
}

#[test]
fn portable_windows_layout_is_recognised() {
    let exe = PathBuf::from("/portable/solidcraft.exe");
    let get = |k: &str| (k == "ProgramFiles").then(|| "C:\\Program Files".to_string());
    let exists = |p: &Path| p == Path::new("/portable/solidcraft-cli.exe");
    assert_eq!(
        detect(&Probe { os: "windows", release_build: true, env: &get, exe: Some(exe), exists: &exists, msi_dir: None }),
        InstallKind::WindowsPortable
    );
}

/// #1870: the installer's wizard can put SolidCraft anywhere, and it puts solidcraft-cli.exe
/// beside it as the portable zip does. The folder it recorded is what tells its copy apart.
#[test]
fn an_msi_install_outside_program_files_is_recognised() {
    let exe = PathBuf::from(r"D:\Program Files\SolidCraft\solidcraft.exe");
    let get = |k: &str| match k {
        "ProgramFiles" | "ProgramW6432" => Some(r"C:\Program Files".to_string()),
        "ProgramFiles(x86)" => Some(r"C:\Program Files (x86)".to_string()),
        _ => None,
    };
    // solidcraft-cli.exe is beside it.
    let exists = |_: &Path| true;
    let kind = |msi_dir: Option<&str>| {
        detect(&Probe { os: "windows", release_build: true, env: &get, exe: Some(exe.clone()), exists: &exists, msi_dir: msi_dir.map(PathBuf::from) })
    };
    // The installer records [INSTALLFOLDER], which ends in a backslash; Windows paths ignore case.
    assert_eq!(kind(Some(r"D:\Program Files\SolidCraft\")), InstallKind::WindowsMsi);
    assert_eq!(kind(Some(r"d:\program files\solidcraft")), InstallKind::WindowsMsi);
    // No installer copy here: the portable zip, as before.
    assert_eq!(kind(None), InstallKind::WindowsPortable);
    assert_eq!(kind(Some("")), InstallKind::WindowsPortable);
    assert_eq!(kind(Some(r"D:\Program Files\SolidCraft2\")), InstallKind::WindowsPortable, "a folder whose name only starts the same");
}

/// The assets of v0.10.0, as published.
fn release() -> Release {
    let names = [
        "SHA256SUMS.txt",
        "solidcraft-0.10.0-linux-x86_64.AppImage",
        "solidcraft-0.10.0-linux-x86_64.AppImage.zsync",
        "solidcraft-0.10.0-linux-x86_64.tar.gz",
        "solidcraft-0.10.0-linux-aarch64.tar.gz",
        "SolidCraft-0.10.0-windows-x64.exe",
        "solidcraft-linux-aarch64.AppImage",
        "solidcraft-linux-aarch64.deb",
        "solidcraft-linux-x86_64.AppImage",
        "solidcraft-linux-x86_64.deb",
        "solidcraft-linux-x86_64.flatpak",
        "solidcraft-linux-x86_64.rpm",
        "solidcraft-linux-x86_64.snap",
        "solidcraft-macos-universal.dmg",
        "solidcraft-windows-arm64-portable.zip",
        "solidcraft-windows-arm64.msi",
        "solidcraft-windows-x64-portable.zip",
        "solidcraft-windows-x64.msi",
        "solidcraft-windows-x86-portable.zip",
        "solidcraft-windows-x86.msi",
    ];
    let assets: Vec<Value> = names
        .iter()
        .map(|n| json!({"name": n, "size": 10, "browser_download_url": format!("https://github.com/bherbruck/solidcraft/releases/download/v0.10.0/{n}")}))
        .collect();
    let body = json!({
        "tag_name": "v0.10.0", "name": "SolidCraft v0.10.0", "body": "**What's new**\n\n- Surface tools.",
        "html_url": "https://github.com/bherbruck/solidcraft/releases/tag/v0.10.0", "draft": false, "prerelease": false, "assets": assets,
    });
    Release::parse(body.to_string().as_bytes()).unwrap()
}

#[test]
fn each_installation_gets_its_own_file() {
    let r = release();
    let name = |k: InstallKind, arch: &str| r.asset_for(&k, arch).map(|a| a.name.clone());
    assert_eq!(name(InstallKind::AppImage("/a".into()), "x86_64").as_deref(), Some("solidcraft-linux-x86_64.AppImage"));
    assert_eq!(name(InstallKind::AppImage("/a".into()), "aarch64").as_deref(), Some("solidcraft-linux-aarch64.AppImage"));
    assert_eq!(name(InstallKind::Deb, "x86_64").as_deref(), Some("solidcraft-linux-x86_64.deb"));
    assert_eq!(name(InstallKind::Rpm, "x86_64").as_deref(), Some("solidcraft-linux-x86_64.rpm"));
    assert_eq!(name(InstallKind::LinuxTarball, "aarch64").as_deref(), Some("solidcraft-0.10.0-linux-aarch64.tar.gz"));
    assert_eq!(name(InstallKind::WindowsMsi, "x86_64").as_deref(), Some("solidcraft-windows-x64.msi"));
    assert_eq!(name(InstallKind::WindowsMsi, "aarch64").as_deref(), Some("solidcraft-windows-arm64.msi"));
    assert_eq!(name(InstallKind::WindowsMsi, "x86").as_deref(), Some("solidcraft-windows-x86.msi"));
    assert_eq!(name(InstallKind::WindowsPortable, "x86_64").as_deref(), Some("solidcraft-windows-x64-portable.zip"));
    assert_eq!(name(InstallKind::WindowsExe, "x86_64").as_deref(), Some("SolidCraft-0.10.0-windows-x64.exe"));
    assert_eq!(name(InstallKind::WindowsExe, "aarch64").as_deref(), Some("solidcraft-windows-arm64-portable.zip"));
    assert_eq!(name(InstallKind::MacApp("/A.app".into()), "aarch64").as_deref(), Some("solidcraft-macos-universal.dmg"));
    assert_eq!(name(InstallKind::Other, "x86_64"), None);
    assert_eq!(name(InstallKind::Deb, "riscv64"), None);
    // Download: the file, or the page when there is none or a package manager updates it.
    assert_eq!(
        r.download_url(&InstallKind::WindowsMsi, "x86_64"),
        "https://github.com/bherbruck/solidcraft/releases/download/v0.10.0/solidcraft-windows-x64.msi"
    );
    assert_eq!(r.download_url(&InstallKind::Other, "x86_64"), "https://github.com/bherbruck/solidcraft/releases/tag/v0.10.0");
    assert_eq!(r.download_url(&InstallKind::Flatpak(APP_ID.into()), "x86_64"), r.page);
    assert_eq!(r.download_url(&InstallKind::Snap { store: true }, "x86_64"), r.page);
    assert_eq!(
        r.download_url(&InstallKind::Snap { store: false }, "x86_64"),
        "https://github.com/bherbruck/solidcraft/releases/download/v0.10.0/solidcraft-linux-x86_64.snap"
    );
    assert_eq!(
        InstallKind::Snap { store: false }.update_command(Some("solidcraft-linux-x86_64.snap")).as_deref(),
        Some("sudo snap install --dangerous ./solidcraft-linux-x86_64.snap")
    );
    assert_eq!(InstallKind::Flatpak(APP_ID.into()).update_command(None).as_deref(), Some("flatpak update io.tangencylabs.solidcraft"));
    assert_eq!(
        InstallKind::Deb.update_command(Some("solidcraft-linux-x86_64.deb")).as_deref(),
        Some("sudo apt install ./solidcraft-linux-x86_64.deb")
    );
    assert_eq!(InstallKind::WindowsMsi.update_command(None), None);
}

#[test]
fn release_answers_are_checked() {
    let r = release();
    assert_eq!((r.tag.as_str(), r.version(), r.assets.len()), ("v0.10.0", "0.10.0", 20));
    let bad = |v: Value| Release::parse(v.to_string().as_bytes()).is_err();
    assert!(bad(json!({"tag_name": "v0.11.0-rc.1", "prerelease": true})));
    assert!(bad(json!({"tag_name": "v0.11.0", "draft": true})));
    assert!(bad(json!({"tag_name": "nightly"})));
    assert!(Release::parse(b"<html>").is_err());
    // Links elsewhere are dropped: the page falls back to the releases page, foreign assets go.
    let r = Release::parse(
        json!({"tag_name": "v1.0.0", "html_url": "https://evil.example/x", "assets": [
            {"name": "solidcraft-windows-x64.msi", "browser_download_url": "https://evil.example/a.msi"},
            {"name": "solidcraft-windows-x86.msi", "browser_download_url": "https://github.com/bherbruck/solidcraft/releases/download/v1.0.0/solidcraft-windows-x86.msi"},
        ]})
        .to_string()
        .as_bytes(),
    )
    .unwrap();
    assert_eq!(r.page, RELEASES_PAGE);
    assert_eq!(r.assets.len(), 1);
    assert_eq!(r.name, "SolidCraft v1.0.0");
    // Huge notes are cut (on a character boundary).
    let r = Release::parse(json!({"tag_name": "v1.0.0", "body": "é".repeat(MAX_NOTES)}).to_string().as_bytes()).unwrap();
    assert!(r.notes.len() <= MAX_NOTES + 8 && r.notes.ends_with('…'));
}

#[test]
fn skip_and_remind_later() {
    let r = release();
    let mut m = Memo::default();
    let now = 1_800_000_000.0;
    assert!(m.offers(&r, "0.9.0", now));
    assert!(!m.offers(&r, "0.10.0", now));
    m.remind_later(now);
    assert!(!m.offers(&r, "0.9.0", now + 3600.0));
    assert!(m.offers(&r, "0.9.0", now + REMIND_DELAY_S + 1.0));
    m.skip(&r);
    assert!(!m.offers(&r, "0.9.0", now + REMIND_DELAY_S + 1.0), "a skipped version stays hidden");
    let mut next = r.clone();
    next.tag = "v0.11.0".into();
    assert!(m.offers(&next, "0.9.0", now + REMIND_DELAY_S + 1.0), "a later version shows again");
}

#[test]
fn every_launch_checks_and_the_open_app_checks_daily() {
    let mut m = Memo::default();
    let now = 1_800_000_000.0;
    assert!(m.due(now, true), "the first start checks");
    m.checked(now, &Ok(release()));
    // Started this morning, checked then: the next start checks again at once.
    assert!(m.due(now + 3600.0, true), "every start checks, whatever the daily schedule says");
    assert!(m.due(now + 5.0, true));
    // While it stays open: once a day.
    assert!(!m.due(now + 3600.0, false));
    assert!(m.due(now + CHECK_INTERVAL_S, false));
    assert!(m.due(now - 2.0 * CHECK_INTERVAL_S, false), "a clock set back doesn't block checks for days");
    // A failed check: the open app tries again an hour later; a new start checks anyway.
    m.checked(now, &Err(FetchError::Failed("offline".into())));
    assert!(!m.due(now + 60.0, false));
    assert!(m.due(now + RETRY_AFTER_FAILURE_S, false));
    assert!(m.due(now + 60.0, true));
}

#[test]
fn the_rate_limit_holds_at_launch_too() {
    let mut m = Memo::default();
    let now = 1_800_000_000.0;
    m.checked(now, &Err(FetchError::RateLimited { retry_after_s: 1800 }));
    assert_eq!(m.rate_limited_until, now + 1800.0);
    for launch in [false, true] {
        assert!(!m.due(now + 1700.0, launch), "GitHub said to wait (launch: {launch})");
        assert!(m.due(now + 1800.0, launch));
    }
    // Absurd waits are capped at a day.
    m.checked(now, &Err(FetchError::RateLimited { retry_after_s: u64::MAX }));
    assert!(!m.due(now + 3600.0, true));
    assert!(m.due(now + CHECK_INTERVAL_S, false));
    // A clock set back more than a day doesn't keep the limit for days.
    assert!(m.due(now - 2.0 * CHECK_INTERVAL_S, true));
}

/// A fresh folder for a test's feed file, removed with it.
struct Scratch(PathBuf);

impl Drop for Scratch {
    fn drop(&mut self) {
        let _ = std::fs::remove_dir_all(&self.0);
    }
}

fn scratch() -> Scratch {
    static N: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
    let n = N.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
    let dir = std::env::temp_dir().join(format!("solidcraft-update-test-{}-{n}", std::process::id()));
    std::fs::create_dir_all(&dir).unwrap();
    Scratch(dir)
}

/// A release one minor version past this build, as the `SOLIDCRAFT_UPDATE_FEED` file gives it.
fn next_release_feed(dir: &Path) -> (PathBuf, String) {
    let mut v = parse_version(current_version()).unwrap();
    v = semver::Version::new(v.major, v.minor + 1, 0);
    let path = dir.join("latest.json");
    let body = json!({
        "tag_name": format!("v{v}"),
        "name": format!("SolidCraft {v}"),
        "body": "## What's new\n\n- Faster rebuilds.",
        "html_url": format!("https://github.com/bherbruck/solidcraft/releases/tag/v{v}"),
        "assets": []
    });
    std::fs::write(&path, body.to_string()).unwrap();
    (path, v.to_string())
}

/// Frames until the check in flight has been collected.
fn wait_for_check(h: &mut crate::scenario::Harness) {
    for _ in 0..500 {
        h.frame();
        if h.app.updater.rx.is_none() && h.app.updater.status != Status::Checking {
            return;
        }
        std::thread::sleep(std::time::Duration::from_millis(2));
    }
    panic!("the update check didn't finish");
}

#[test]
fn a_new_launch_checks_even_when_the_last_check_was_today() {
    let dir = scratch();
    let (feed, version) = next_release_feed(&dir.0);
    let mut h = crate::scenario::Harness::new();
    // Yesterday's version was started and checked this morning: no check due until tomorrow.
    let now = unix_now();
    h.app.preferences.update.last_check = now - 3600.0;
    h.app.preferences.update.next_check = now + CHECK_INTERVAL_S - 3600.0;
    h.app.updater.feed = Some(feed);
    h.frame();
    assert_eq!(h.app.updater.status, Status::Checking, "the launch checks at once");
    wait_for_check(&mut h);
    assert_eq!(h.app.updater.release.as_ref().map(|r| r.version().to_string()), Some(version.clone()));
    assert!(h.app.preferences.update.next_check > now + CHECK_INTERVAL_S - 60.0, "the next check is a day later");
    // While the app stays open it doesn't ask again before then.
    h.frames(5);
    assert!(h.app.updater.rx.is_none() && h.app.updater.status == Status::Idle);
}

#[test]
fn turning_off_automatic_checks_stops_the_launch_check() {
    let dir = scratch();
    let (feed, _) = next_release_feed(&dir.0);
    let mut h = crate::scenario::Harness::new();
    h.app.preferences.check_updates = false;
    h.app.updater.feed = Some(feed);
    h.frames(3);
    assert_eq!(h.app.updater.status, Status::Idle);
    assert!(h.app.updater.release.is_none());
}

#[test]
fn help_menu_checks_with_automatic_checks_off_and_offers_installation() {
    let dir = scratch();
    let (feed, version) = next_release_feed(&dir.0);
    let mut h = crate::scenario::Harness::new();
    h.app.preferences.check_updates = false;
    h.app.preferences.update.skipped = format!("v{version}");
    h.app.preferences.update.remind_after = unix_now() + REMIND_DELAY_S;
    h.app.updater.feed = Some(feed);
    h.app.updater.kind = Some(InstallKind::MacApp("/Applications/SolidCraft.app".into()));
    h.app.updater.managed = Some(None);
    h.app.services.http_get = Some(Arc::new(|_| panic!("the check must use the test feed")));
    h.app.services.http_download = Some(Arc::new(|_, _, _| panic!("offering an update must not install it")));
    h.app.help.menu = true;
    h.frames(2);
    let [x, y] = h.widget("Check for updates").expect("the Help menu has an update check");
    h.call("ui.click", json!({"x": x, "y": y}));
    wait_for_check(&mut h);
    h.frames(2);
    assert!(!h.app.help.menu);
    assert!(h.app.updater.open);
    assert!(h.app.preferences.update.skipped.is_empty());
    assert_eq!(h.app.preferences.update.remind_after, 0.0);
    assert!(h.widget(&format!("SolidCraft {version} is available")).is_some());
    assert!(h.widget("Download and open").is_some(), "the macOS installation is offered immediately");
    assert!(h.app.updater.job.is_none());
}

/// Hold an automatic check at its result channel so the manual request can join it without
/// a second HTTP request or a wall-clock race.
fn pending_check() -> (crate::scenario::Harness, std::sync::mpsc::Sender<Result<Release, FetchError>>) {
    let mut h = crate::scenario::Harness::new();
    h.app.preferences.check_updates = false;
    h.app.updater.kind = Some(InstallKind::WindowsMsi);
    h.app.services.http_get = Some(Arc::new(|_| panic!("do not start a second check")));
    let (tx, rx) = std::sync::mpsc::channel();
    h.app.updater.rx = Some((rx, false));
    h.app.updater.status = Status::Checking;
    (h, tx)
}

#[test]
fn help_check_shows_progress_and_up_to_date_then_closes() {
    let (mut h, tx) = pending_check();
    h.call("ui.help", json!({"item": "updates"}));
    assert!(h.app.updater.open);
    assert!(h.app.updater.rx.as_ref().unwrap().1, "the in-flight automatic check becomes manual");
    assert!(h.widget("Checking…").is_some());
    let release = Release::parse(
        json!({"tag_name": format!("v{}", comparable(&parse_version(current_version()).unwrap())), "assets": []}).to_string().as_bytes(),
    )
    .unwrap();
    tx.send(Ok(release)).unwrap();
    h.frames(2);
    assert_eq!(h.app.updater.status, Status::UpToDate);
    assert!(h.widget("SolidCraft is up to date.").is_some());
    assert!(h.widget("Download").is_none() && h.widget("Update now").is_none());
    let [x, y] = h.widget("Close").unwrap();
    h.call("ui.click", json!({"x": x, "y": y}));
    assert!(!h.app.updater.open);
    // Reopening during the cooldown still shows the result, without another request.
    h.app.updater.last_manual = unix_now();
    h.call("ui.help", json!({"item": "updates"}));
    assert!(h.widget("SolidCraft is up to date.").is_some());
    assert!(h.app.updater.rx.is_none());
}

#[test]
fn help_check_reports_network_errors_and_rate_limits_in_the_window() {
    for error in [FetchError::Failed("offline".into()), FetchError::RateLimited { retry_after_s: 3600 }] {
        let (mut h, tx) = pending_check();
        h.call("ui.help", json!({"item": "updates"}));
        tx.send(Err(error.clone())).unwrap();
        h.frames(2);
        assert_eq!(h.app.updater.status, Status::Failed(error.to_string()));
        assert!(h.widget(&format!("Couldn't check: {error}")).is_some());
        assert!(h.widget("SolidCraft is up to date.").is_none());
        if matches!(error, FetchError::RateLimited { .. }) {
            h.call("ui.help", json!({"item": "updates"}));
            assert!(h.app.updater.rx.is_none(), "the server's rate limit is honoured");
            assert!(matches!(h.app.updater.status, Status::Failed(_)));
        }
    }
}

#[test]
fn help_check_result_follows_the_selected_language() {
    let (mut h, tx) = pending_check();
    h.call("ui.prefs", json!({"language": "de"}));
    h.call("ui.help", json!({"item": "updates"}));
    let release = Release::parse(json!({"tag_name": current_version(), "assets": []}).to_string().as_bytes()).unwrap();
    tx.send(Ok(release)).unwrap();
    h.frames(2);
    assert!(h.widget("SolidCraft ist aktuell.").is_some());
    for (language, title, message) in [
        ("fr", "Rechercher des mises à jour", "SolidCraft est à jour."),
        ("ja", "アップデートを確認", "SolidCraft は最新です。"),
        ("zh-TW", "檢查更新", "SolidCraft 已是最新版本。"),
    ] {
        h.call("ui.prefs", json!({"language": language}));
        assert!(h.widget(title).is_some(), "the window title follows {language}");
        assert!(h.widget(message).is_some(), "the result follows {language}");
        assert!(h.widget("SolidCraft is up to date.").is_none());
    }
}

#[test]
fn help_check_explains_when_checks_are_unavailable() {
    let mut h = crate::scenario::Harness::new();
    h.app.updater.off = true;
    h.call("ui.help", json!({"item": "updates"}));
    assert!(h.widget("Update checks are not available for this installation.").is_some());
    assert!(h.widget("SolidCraft is up to date.").is_none());
    assert!(h.app.updater.rx.is_none());
}

#[test]
fn closing_a_manual_check_does_not_reopen_it_when_an_update_arrives() {
    let (mut h, tx) = pending_check();
    h.call("ui.help", json!({"item": "updates"}));
    let [x, y] = h.widget("Close").unwrap();
    h.call("ui.click", json!({"x": x, "y": y}));
    assert!(!h.app.updater.open);
    let release = Release::parse(br#"{"tag_name":"v999.0.0","assets":[]}"#).unwrap();
    tx.send(Ok(release)).unwrap();
    h.frames(2);
    assert!(!h.app.updater.open);
    assert!(offered(&h.app).is_some(), "the update remains available from the title bar");
}

#[test]
fn help_check_keeps_an_active_installation_on_screen() {
    let (mut h, dir) = open_update_window(None);
    let (_tx, rx) = std::sync::mpsc::channel();
    h.app.updater.job = Some((rx, Arc::new(install::Progress::default())));
    h.app.updater.open = false;
    h.call("ui.help", json!({"item": "updates"}));
    assert!(h.app.updater.open && h.app.updater.job.is_some());
    assert!(h.app.updater.rx.is_none());
    assert!(h.widget("Cancel").is_some());
    drop(dir);
}

#[test]
fn the_title_bar_offers_the_new_version_and_opens_the_update_window() {
    let dir = scratch();
    let (feed, version) = next_release_feed(&dir.0);
    let mut h = crate::scenario::Harness::new();
    let report = crate::scenario::rect_of("titlebar:report").unwrap();
    assert!(crate::scenario::rect_of("titlebar:update").is_none(), "nothing offered before a check");
    h.app.updater.feed = Some(feed);
    h.frame();
    wait_for_check(&mut h);
    h.frames(2);
    // An accent pill reading "Update to <version>", left of the Settings/Help/Report cluster.
    let label = format!("Update to {version}");
    let at = h.widget(&label).unwrap_or_else(|| panic!("no `{label}` in the title bar"));
    let pill = crate::scenario::rect_of("titlebar:update").unwrap();
    assert!(pill.contains(egui::pos2(at[0] as f32, at[1] as f32)));
    let assistant = crate::scenario::rect_of("titlebar:assistant").unwrap();
    assert!(pill.right() < assistant.left() && assistant.left() - pill.right() < 12.0, "beside Assistant: {pill:?} {assistant:?}");
    assert!((pill.center().y - report.center().y).abs() < 1.0 && pill.height() <= report.height());
    assert_eq!(crate::scenario::rect_of("titlebar:report"), Some(report), "Report a bug stays where it was");
    assert!(!h.app.updater.open, "no window pops up by itself");
    assert!(crate::scenario::rect_of("update:window").is_none());
    // Clicking it opens the Update window (not a modal: the bar stays usable).
    h.call("ui.click", json!({"x": pill.center().x, "y": pill.center().y}));
    h.frames(2);
    assert!(h.app.updater.open);
    assert!(h.widget("Skip this version").is_some() && h.widget("Remind me later").is_some());
    // Remind me later hides the pill.
    let later = h.widget("Remind me later").unwrap();
    h.call("ui.click", json!({"x": later[0], "y": later[1]}));
    h.frames(2);
    assert!(!h.app.updater.open);
    assert!(h.widget(&label).is_none(), "Remind me later hides it");
}

#[test]
fn the_pill_shortens_in_a_narrow_title_bar() {
    let dir = scratch();
    let (feed, version) = next_release_feed(&dir.0);
    let mut h = crate::scenario::Harness::new();
    h.app.updater.feed = Some(feed);
    h.frame();
    wait_for_check(&mut h);
    let wide = crate::scenario::rect_of("titlebar:update").unwrap();
    let label = format!("Update to {version}");
    assert!(h.widget(&label).is_some());
    // Narrower and narrower: the pill never grows, never reaches Report a bug, and its label gives
    // way (to "Update", then the icon alone) before the document tabs run out of room.
    let mut last = wide.width();
    let mut shortened = false;
    for width in [1000.0, 800.0, 700.0, 600.0, 520.0, 440.0] {
        h.call("ui.resize", json!({"width": width, "height": 600}));
        h.frames(3);
        let report = crate::scenario::rect_of("titlebar:report").unwrap();
        // Icon alone, it keeps the full text for screen readers.
        let pill = crate::scenario::rect_of("titlebar:update").filter(|_| h.widget(&label).is_some() || h.widget("Update").is_some());
        if let Some(p) = pill {
            assert!(p.width() <= last + 0.5, "at {width}: {p:?} grew from {last}");
            assert!(p.right() <= report.left(), "at {width}: {p:?} overlaps Report a bug {report:?}");
            last = p.width();
        }
        shortened |= pill.is_none_or(|p| p.width() < wide.width());
        if width == 1000.0 {
            assert!(h.widget("Update").is_some() && h.widget(&label).is_none(), "the short label keeps room for the tabs");
        }
    }
    assert!(shortened, "the long label gives way in a narrow bar");
}

#[test]
fn the_memo_survives_with_the_preferences() {
    let mut p = crate::prefs::Prefs::default();
    assert!(p.check_updates);
    p.update.skipped = "0.10.0".into();
    p.update.remind_after = 5.0;
    let back: crate::prefs::Prefs = serde_json::from_str(&serde_json::to_string(&p).unwrap()).unwrap();
    assert_eq!(back, p);
    // Older preferences without these fields load with the defaults.
    let old: crate::prefs::Prefs = serde_json::from_str(r#"{"theme":"light"}"#).unwrap();
    assert!(old.check_updates && old.update == Memo::default());
}

#[test]
fn release_notes_read_as_markdown() {
    let md = "## What's new\n\n**Why 0.10:** a minor\nbump.\n\n- **Surface tools.** Revolve and `solidcraft-cli mcp`\n  continued ([#925](https://x/925)).\n  - nested\n* Fix by @a in https://github.com/bherbruck/solidcraft/pull/1064\n\nSee https://example.com/x.";
    let b = parse_markdown(md);
    assert_eq!(b.first(), Some(&Block::Heading(vec![Span::Text("What's new".into())])));
    assert_eq!(b.get(1), Some(&Block::Paragraph(vec![Span::Strong("Why 0.10:".into()), Span::Text(" a minor bump.".into())])));
    assert_eq!(
        b.get(2),
        Some(&Block::Item(
            0,
            vec![
                Span::Strong("Surface tools.".into()),
                Span::Text(" Revolve and ".into()),
                Span::Code("solidcraft-cli mcp".into()),
                Span::Text(" continued (".into()),
                Span::Link { text: "#925".into(), url: Some("https://x/925".into()) },
                Span::Text(").".into()),
            ]
        ))
    );
    assert_eq!(b.get(3), Some(&Block::Item(1, vec![Span::Text("nested".into())])));
    assert_eq!(
        b.get(4),
        Some(&Block::Item(
            0,
            vec![
                Span::Text("Fix by @a in ".into()),
                Span::Link { text: "#1064".into(), url: Some("https://github.com/bherbruck/solidcraft/pull/1064".into()) }
            ]
        ))
    );
    assert_eq!(b.get(5), Some(&Block::Paragraph(vec![Span::Text("See https://example.com/x.".into())])));
    // Unclosed markers and odd input show as written, without panicking.
    for s in ["**open", "`tick", "[a](b", "[a]", "#", "- ", "é**", "https://github.com/", "**[x](y)**"] {
        let _ = parse_markdown(s);
    }
    assert_eq!(inline("**[x](y)**"), vec![Span::Strong("x".into())]);
}

/// #2943: a release note's links keep where they go, so the window can open them; only web
/// addresses are kept (a relative or other link shows as text that opens nothing).
#[test]
fn release_note_links_keep_their_web_targets() {
    let spans = inline("[guide](https://docs.solidcraft.io/guide) and [file](file:///etc/passwd) and [rel](../x)");
    let links: Vec<(String, Option<String>)> =
        spans.into_iter().filter_map(|s| if let Span::Link { text, url } = s { Some((text, url)) } else { None }).collect();
    assert_eq!(links, vec![("guide".into(), Some("https://docs.solidcraft.io/guide".into())), ("file".into(), None), ("rel".into(), None)]);
}

#[test]
fn releases_under_either_owner_are_accepted() {
    let parse = |owner: &str| {
        let base = format!("https://github.com/{owner}/releases");
        Release::parse(
            json!({"tag_name": "v1.0.0", "html_url": format!("{base}/tag/v1.0.0"), "assets": [
                {"name": "solidcraft-windows-x64.msi", "browser_download_url": format!("{base}/download/v1.0.0/solidcraft-windows-x64.msi")},
            ]})
            .to_string()
            .as_bytes(),
        )
        .unwrap()
    };
    for owner in ["bherbruck/solidcraft", "tangency-labs/solidcraft"] {
        let r = parse(owner);
        assert_eq!(r.page, format!("https://github.com/{owner}/releases/tag/v1.0.0"));
        assert_eq!(r.assets.len(), 1, "{owner}");
    }
    // Any other owner, repository, host or scheme is dropped.
    for owner in ["evil/solidcraft", "tangency-labs/solidcraft-evil", "tangency-labs.evil/solidcraft", "bherbruck/other"] {
        let r = parse(owner);
        assert_eq!(r.page, RELEASES_PAGE, "{owner}");
        assert!(r.assets.is_empty(), "{owner}");
    }
    assert!(!is_release_url("http://github.com/tangency-labs/solidcraft/releases/x"));
    assert!(!is_release_url("https://github.com.evil.example/tangency-labs/solidcraft/releases/x"));
    assert!(!is_release_url("https://github.com/tangency-labs/solidcraft/issues/1"));
}

#[test]
fn the_version_links_to_its_release_notes() {
    // A release build opens the page of its own release; stable, candidate and nightly tags all exist.
    for v in ["0.17.0", "0.21.0-rc.2", "0.20.0-nightly.20261023.69.1"] {
        assert_eq!(release_notes_url(v, true), format!("https://github.com/tangency-labs/solidcraft/releases/tag/v{v}"));
    }
    // A development build has no release of its own: the release history, which is what the issue asks for.
    assert_eq!(release_notes_url("0.17.0", false), "https://github.com/tangency-labs/solidcraft/releases");
    // Anything that is not a version never ends up in a URL.
    assert_eq!(release_notes_url("0.1/../../x", true), "https://github.com/tangency-labs/solidcraft/releases");
}

#[test]
fn unavailable_preferences_show_disabled_update_controls_and_real_values() {
    use egui::accesskit::{Role, Toggled};
    let _language = crate::i18n::scope("en");
    for kind in [InstallKind::Dev, InstallKind::Web, InstallKind::Flatpak("io.solidcraft.SolidCraft".into())] {
        for checked in [false, true] {
            let mut h = crate::scenario::Harness::new();
            h.app.home.open = false;
            h.app.preferences.language = "en".into();
            h.app.preferences.check_updates = checked;
            h.app.updater.kind = Some(kind.clone());
            h.app.updater.feed = None;
            assert!(!available(&mut h.app));
            let memo = h.app.preferences.update.clone();
            let launch_checked = h.app.updater.launch_checked;
            let last_manual = h.app.updater.last_manual;
            h.call("ui.prefs", json!({"open":"General"}));
            crate::prefs::reveal_preference(&mut h, "prefs:check_updates");
            let body = crate::scenario::rect_of("prefs:page_body").unwrap();
            let button = crate::scenario::rect_of("prefs:check_now").unwrap();
            assert!(body.contains_rect(button));
            assert!(body.contains_rect(crate::scenario::rect_of("prefs:check_updates").unwrap()));
            let tree = h.output.accesskit_update.as_ref().unwrap();
            for (label, role) in [("Check now", Role::Button), ("Check at start and once a day", Role::CheckBox)] {
                let controls: Vec<_> = tree.nodes.iter().filter(|(_, node)| node.role() == role && node.label() == Some(label)).collect();
                assert_eq!(controls.len(), 1, "{kind:?}: one {label} control");
                assert!(controls[0].1.is_disabled(), "{kind:?}: {label} is disabled");
                if role == Role::CheckBox {
                    assert_eq!(controls[0].1.toggled(), Some(if checked { Toggled::True } else { Toggled::False }));
                }
            }
            let reason = crate::i18n::tr("update.check_unavailable");
            assert_eq!(tree.nodes.iter().filter(|(_, node)| node.role() == Role::Label && node.value() == Some(reason)).count(), 1);
            let texts: Vec<_> = h
                .shapes
                .iter()
                .filter_map(|shape| if let egui::Shape::Text(text) = &shape.shape { Some(text.galley.text()) } else { None })
                .collect();
            assert!(texts.contains(&reason), "{kind:?}: the unavailable reason is painted");
            assert!(h.widget("Up to date").is_none(), "unavailability is not a successful check");
            let note = match &kind {
                InstallKind::Web => crate::i18n::tr("update.prefs_web").to_string(),
                InstallKind::Flatpak(id) => {
                    crate::i18n::format("update.prefs_flatpak", &[("version", current_version()), ("command", &format!("flatpak update {id}"))])
                }
                _ => crate::i18n::format("update.prefs_dev", &[("version", current_version())]),
            };
            assert!(
                tree.nodes.iter().any(|(_, node)| node.role() == Role::Label && node.value() == Some(note.as_str())),
                "the platform help stays accessible"
            );
            assert!(!texts.contains(&note.as_str()), "the longer explanation stays in hover help");
            assert!(crate::scenario::rect_of("prefs:updates_help").is_some());
            h.step(&json!({"click":{"handle":"prefs:check_now"}})).unwrap();
            h.step(&json!({"widget":"Check at start and once a day"})).unwrap();
            assert_eq!(h.app.preferences.check_updates, checked);
            assert_eq!(h.app.preferences.update, memo);
            assert_eq!(h.app.updater.status, Status::Idle);
            assert_eq!(h.app.updater.launch_checked, launch_checked);
            assert_eq!(h.app.updater.last_manual, last_manual);
            assert!(h.app.updater.rx.is_none() && h.app.updater.job.is_none() && h.app.updater.release.is_none());
            assert!(!h.app.updater.open, "attempting the disabled action does not open the checker");
        }
    }
}

#[test]
fn general_updates_show_real_status_and_time_and_check_now_uses_the_existing_feed() {
    let dir = scratch();
    let (feed, version) = next_release_feed(&dir.0);
    let mut h = crate::scenario::Harness::new();
    h.app.home.open = false;
    h.app.preferences.language = "en".into();
    h.app.preferences.check_updates = false;
    h.app.preferences.update.last_check = 1_700_000_000.0;
    h.app.updater.feed = Some(feed);
    h.app.updater.kind = Some(InstallKind::WindowsMsi);
    h.app.updater.managed = Some(None);
    h.app.updater.status = Status::UpToDate;
    h.call("ui.prefs", json!({"open":"General"}));
    crate::prefs::reveal_preference(&mut h, "prefs:check_now");
    let tree = h.output.accesskit_update.as_ref().unwrap();
    for (label, role) in [("Check now", egui::accesskit::Role::Button), ("Check at start and once a day", egui::accesskit::Role::CheckBox)] {
        let controls: Vec<_> = tree.nodes.iter().filter(|(_, node)| node.role() == role && node.label() == Some(label)).collect();
        assert_eq!(controls.len(), 1);
        assert!(!controls[0].1.is_disabled(), "available update controls stay enabled");
        if role == egui::accesskit::Role::CheckBox {
            assert_eq!(controls[0].1.toggled(), Some(egui::accesskit::Toggled::False));
        }
    }
    let checked = crate::i18n::format("prefs.general.last_check", &[("time", &solidcraft_engine::crash::utc(1_700_000_000))]);
    assert!(h.widget(&checked).is_some(), "the persisted check time is shown");
    let button = crate::scenario::rect_of("prefs:check_now").unwrap();
    h.step(&json!({"click":[button.center().x, button.center().y]})).unwrap();
    wait_for_check(&mut h);
    assert_eq!(h.app.updater.release.as_ref().map(|r| r.version().to_string()), Some(version));
    assert!(h.app.preferences.update.last_check > 1_700_000_000.0);
    assert!(!h.app.preferences.check_updates, "a manual check keeps the schedule preference");
}

fn no_env(_: &str) -> Option<String> {
    None
}

fn record(path: &str) -> Vec<u8> {
    json!({"apps": {"solidcraft": {"version": "0.25.1", "kind": "AppImage", "path": path, "installed_at": 1}}}).to_string().into_bytes()
}

#[test]
fn the_variable_names_the_manager() {
    let nothing = |_: &Path| None;
    let kind = InstallKind::LinuxTarball;
    let with = |value: &'static str| {
        let env = move |k: &str| (k == MANAGED_ENV).then(|| value.to_string());
        managed_by("linux", &env, Some(Path::new("/opt/sc/solidcraft")), &kind, &nothing)
    };
    assert_eq!(with("ArtCraft Launcher").as_deref(), Some("ArtCraft Launcher"));
    assert_eq!(with("  Other \u{7}Manager\n").as_deref(), Some("Other Manager"), "padding and control characters are dropped");
    assert_eq!(with("   "), None, "an empty value is not a manager");
    assert_eq!(with(&"x".repeat(500).leak()[..]).map(|n| n.len()), Some(64), "a long name is cut");
    assert_eq!(managed_by("linux", &no_env, Some(Path::new("/opt/sc/solidcraft")), &kind, &nothing), None);
}

#[test]
fn the_launchers_record_marks_the_install_it_made() {
    let exe = Path::new("/home/me/Apps/SolidCraft.AppImage");
    let appimage = InstallKind::AppImage(exe.to_path_buf());
    let env = |k: &str| (k == "HOME").then(|| "/home/me".to_string());
    let seen = std::cell::RefCell::new(Vec::new());
    let read = |bytes: Vec<u8>| {
        let seen = &seen;
        move |p: &Path| {
            seen.borrow_mut().push(p.to_path_buf());
            Some(bytes.clone())
        }
    };
    // The AppImage the launcher recorded; the running executable is inside its mount.
    let run = |path: &str| managed_by("linux", &env, Some(Path::new("/tmp/.mount_SolidXYZ/usr/bin/solidcraft")), &appimage, &read(record(path)));
    assert_eq!(run("/home/me/Apps/SolidCraft.AppImage").as_deref(), Some("ArtCraft Launcher"));
    assert_eq!(seen.borrow().as_slice(), [PathBuf::from("/home/me/.local/share/artcraft-launcher/installed.json")]);
    // Another copy, a prefix that is not a folder of ours, the root and a relative path are not ours.
    assert_eq!(run("/home/me/Apps/Other.AppImage"), None);
    assert_eq!(run("/home/me/Apps/SolidCraft.AppImage.old"), None);
    assert_eq!(run("/"), None);
    assert_eq!(run("Apps/SolidCraft.AppImage"), None);
    // No record, a damaged one, one without SolidCraft, and a record file of any other shape.
    let one = |bytes: &'static [u8]| managed_by("linux", &env, Some(exe), &appimage, &|_: &Path| Some(bytes.to_vec()));
    assert_eq!(one(b"{not json"), None);
    assert_eq!(one(br#"{"apps": {"photocraft": {"path": "/home/me/Apps/SolidCraft.AppImage"}}}"#), None);
    assert_eq!(one(br#"{"apps": {"solidcraft": {"path": 7}}}"#), None);
    assert_eq!(one(b"[]"), None);
    assert_eq!(managed_by("linux", &env, Some(exe), &appimage, &|_: &Path| None), None);
    // XDG_DATA_HOME moves the record.
    let xdg = |k: &str| (k == "XDG_DATA_HOME").then(|| "/data".to_string());
    let paths = std::cell::RefCell::new(Vec::new());
    managed_by("linux", &xdg, Some(exe), &appimage, &|p: &Path| {
        paths.borrow_mut().push(p.to_path_buf());
        None
    });
    assert_eq!(paths.into_inner(), [PathBuf::from("/data/artcraft-launcher/installed.json")]);
}

#[test]
fn the_record_matches_folders_bundles_and_windows_paths() {
    let nothing_else = |bytes: Vec<u8>| move |_: &Path| Some(bytes.clone());
    // An unpacked tarball: the record names the folder, and the launcher's own HOME is no help,
    // so the record is found beside the `apps` folder the app runs from.
    let exe = Path::new("/home/me/.local/share/artcraft-launcher/apps/solidcraft/bin/solidcraft");
    let read = |p: &Path| {
        (p == Path::new("/home/me/.local/share/artcraft-launcher/installed.json"))
            .then(|| record("/home/me/.local/share/artcraft-launcher/apps/solidcraft"))
    };
    let home = |k: &str| (k == "HOME").then(|| "/home/me/.local/share/artcraft-launcher/apps/solidcraft/home".to_string());
    assert_eq!(managed_by("linux", &home, Some(exe), &InstallKind::LinuxTarball, &read).as_deref(), Some("ArtCraft Launcher"));
    // macOS: the bundle.
    let bundle = PathBuf::from("/Applications/SolidCraft.app");
    let mac = InstallKind::MacApp(bundle.clone());
    let exe = Path::new("/Applications/SolidCraft.app/Contents/MacOS/solidcraft");
    let home = |k: &str| (k == "HOME").then(|| "/Users/me".to_string());
    let read = |p: &Path| {
        assert_eq!(p, Path::new("/Users/me/Library/Application Support/ArtCraft Launcher/installed.json"));
        Some(record("/Applications/SolidCraft.app"))
    };
    assert_eq!(managed_by("macos", &home, Some(exe), &mac, &read).as_deref(), Some("ArtCraft Launcher"));
    // Windows: case and the verbatim prefix don't matter, and the record is under LOCALAPPDATA.
    let local = |k: &str| (k == "LOCALAPPDATA").then(|| r"C:\Users\me\AppData\Local".to_string());
    let exe = Path::new(r"C:\Users\me\AppData\Local\Programs\SolidCraft\solidcraft.exe");
    let read = nothing_else(record(r"\\?\c:\users\me\appdata\local\programs\solidcraft\SOLIDCRAFT.EXE"));
    assert_eq!(managed_by("windows", &local, Some(exe), &InstallKind::WindowsExe, &read).as_deref(), Some("ArtCraft Launcher"));
    let read = nothing_else(record(r"C:\Users\me\AppData\Local\Programs\SolidCraft2"));
    assert_eq!(managed_by("windows", &local, Some(exe), &InstallKind::WindowsExe, &read), None, "a folder whose name only starts the same");
    // Linux paths are case-sensitive.
    let read = nothing_else(record("/OPT/SC"));
    assert_eq!(managed_by("linux", &no_env, Some(Path::new("/opt/sc/solidcraft")), &InstallKind::LinuxTarball, &read), None);
}

/// A harness with a newer release found and the Update window open, on an AppImage that a
/// launcher may manage. The host can download, so the one-click update is on offer unless managed.
fn open_update_window(managed: Option<&str>) -> (crate::scenario::Harness, Scratch) {
    let dir = scratch();
    let (feed, _) = next_release_feed(&dir.0);
    let mut h = crate::scenario::Harness::new();
    let get: HttpGet = Arc::new(|_| Err(FetchError::Failed("offline".into())));
    let download: install::HttpDownload = Arc::new(|_, _, _| Err(FetchError::Failed("offline".into())));
    h.app.services.http_get = Some(get);
    h.app.services.http_download = Some(download);
    h.app.updater.kind = Some(InstallKind::AppImage("/home/me/SolidCraft.AppImage".into()));
    h.app.updater.managed = Some(managed.map(str::to_string));
    h.app.updater.feed = Some(feed);
    h.frame();
    wait_for_check(&mut h);
    h.frames(2);
    h.app.updater.open = true;
    h.frames(3);
    (h, dir)
}

#[test]
fn a_managed_install_points_to_its_manager_instead_of_updating_itself() {
    let (mut h, _dir) = open_update_window(Some("ArtCraft Launcher"));
    assert_eq!(install_method(&mut h.app), None, "no AppImage self-replace");
    assert!(h.widget("Update available: update SolidCraft in ArtCraft Launcher").is_some());
    for gone in ["Update now", "Download", "Open release page"] {
        assert!(h.widget(gone).is_none(), "{gone} is not offered");
    }
    assert!(h.widget("Skip this version").is_some() && h.widget("Remind me later").is_some());
    // It still checked and still shows the pill.
    assert!(h.app.updater.release.is_some() && offered(&h.app).is_some());
    assert!(crate::scenario::rect_of("titlebar:update").is_some());
}

#[test]
fn an_unmanaged_install_updates_itself_as_before() {
    let (mut h, _dir) = open_update_window(None);
    assert_eq!(install_method(&mut h.app), Some(install::Method::AppImage("/home/me/SolidCraft.AppImage".into())));
    assert!(h.widget("Update now").is_some());
    assert!(h.widget("Download").is_some());
    assert!(h.widget("Update available: update SolidCraft in ArtCraft Launcher").is_none());
}

#[test]
fn periodic_checks_refresh_the_offered_label() {
    let dir = scratch();
    let (feed, first) = next_release_feed(&dir.0);
    let mut h = crate::scenario::Harness::new();
    h.app.updater.feed = Some(feed.clone());
    h.frame();
    wait_for_check(&mut h);
    h.frames(2);
    assert!(h.widget(&format!("Update to {first}")).is_some());
    h.app.updater.installed = Some(Ok(install::Outcome::Restart(dir.0.join("SolidCraft.AppImage"))));
    let v = parse_version(&first).unwrap();
    let next = format!("{}.{}.0", v.major, v.minor + 1);
    std::fs::write(feed, json!({"tag_name": format!("v{next}")}).to_string()).unwrap();
    h.app.preferences.update.next_check = 0.0;
    h.frame();
    wait_for_check(&mut h);
    h.frames(2);
    assert!(h.widget(&format!("Update to {next}")).is_some());
    assert!(h.widget(&format!("Update to {first}")).is_none());
}

#[test]
fn install_selection_refreshes_the_button_and_progress_before_completion() {
    let dir = scratch();
    let target = dir.0.join("SolidCraft.AppImage");
    let name = asset_name(&InstallKind::AppImage(target.clone()), std::env::consts::ARCH, "999.1.0").unwrap();
    let mut h = crate::scenario::Harness::new();
    h.app.preferences.check_updates = false;
    let mut shown = release();
    shown.tag = "v999.0.0".into();
    h.app.updater.release = Some(shown);
    h.app.updater.kind = Some(InstallKind::AppImage(target));
    h.app.updater.open = true;
    h.app.services.http_get = Some(Arc::new(move |url| {
        if url == LATEST_API {
            return Ok(json!({"tag_name":"v999.1.0", "assets":[
                {"name": name, "browser_download_url":format!("https://github.com/tangency-labs/solidcraft/releases/download/v999.1.0/{name}")},
                {"name": install::SUMS, "browser_download_url":"https://github.com/tangency-labs/solidcraft/releases/download/v999.1.0/SHA256SUMS.txt"}
            ]}).to_string().into_bytes());
        }
        Ok(format!("{}  {name}\n", "a".repeat(64)).into_bytes())
    }));
    let (tx, rx) = std::sync::mpsc::channel();
    let rx = std::sync::Mutex::new(rx);
    h.app.services.http_download = Some(Arc::new(move |_, _, _| {
        rx.lock().unwrap().recv().unwrap();
        Err(FetchError::Failed("download stopped".into()))
    }));
    start_install(&mut h.app, &egui::Context::default());
    for _ in 0..500 {
        poll_install(&mut h.app);
        if h.app.updater.release.as_ref().unwrap().version() == "999.1.0" {
            break;
        }
        std::thread::sleep(std::time::Duration::from_millis(2));
    }
    h.frames(2);
    assert!(h.widget("Update to 999.1.0").is_some());
    assert!(h.widget("Updating to 999.1.0.").is_some());
    assert!(h.app.updater.installed.is_none());
    tx.send(()).unwrap();
}

#[test]
fn cancel_download_leaves_downloading_immediately() {
    // Cancel must clear the job from the UI at once so the card leaves "Downloading" without
    // waiting for a stalled feed or checksum GET (#8908).
    let dir = scratch();
    let target = dir.0.join("SolidCraft.AppImage");
    let name = asset_name(&InstallKind::AppImage(target.clone()), std::env::consts::ARCH, "999.1.0").unwrap();
    let mut h = crate::scenario::Harness::new();
    h.app.preferences.check_updates = false;
    let mut shown = release();
    shown.tag = "v999.0.0".into();
    h.app.updater.release = Some(shown);
    h.app.updater.kind = Some(InstallKind::AppImage(target));
    h.app.updater.open = true;
    let (gate_tx, gate_rx) = std::sync::mpsc::channel();
    let gate_rx = std::sync::Mutex::new(gate_rx);
    h.app.services.http_get = Some(Arc::new(move |url| {
        if url == LATEST_API {
            return Ok(json!({"tag_name":"v999.1.0", "assets":[
                {"name": name, "browser_download_url":format!("https://github.com/tangency-labs/solidcraft/releases/download/v999.1.0/{name}")},
                {"name": install::SUMS, "browser_download_url":"https://github.com/tangency-labs/solidcraft/releases/download/v999.1.0/SHA256SUMS.txt"}
            ]}).to_string().into_bytes());
        }
        // Stall checksum GET until the test ends so Cancel has to work before the body download.
        let _ = gate_rx.lock().unwrap().recv();
        Ok(format!("{}  {name}\n", "a".repeat(64)).into_bytes())
    }));
    h.app.services.http_download = Some(Arc::new(|_, _, _| Err(FetchError::Failed("download must not start".into()))));
    start_install(&mut h.app, &egui::Context::default());
    assert!(h.app.updater.job.is_some());
    h.frames(2);
    let cancel = h.widget("Cancel").expect("Cancel while Downloading");
    h.call("ui.click", json!({"x": cancel[0], "y": cancel[1]}));
    assert!(h.app.updater.job.is_none(), "Cancel clears the job immediately");
    assert!(h.app.updater.installed.is_none());
    assert!(h.app.updater.open, "Cancel leaves the Update window open on Offer");
    h.frames(2);
    assert!(
        h.widget("Remind me later").is_some() || h.widget("Skip this version").is_some() || h.widget("Update now").is_some(),
        "Offer returns after Cancel"
    );
    assert!(h.widget("Updating to 999.1.0.").is_none());
    let _ = gate_tx.send(());
}