diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index c235ebd3bf..fb1f478b4d 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -522,3 +522,54 @@ jobs: echo sed 's/^/ /' SHA256SUMS.txt } >>"$GITHUB_STEP_SUMMARY" + - name: Update manifest (latest.json) + working-directory: artifacts + # What Help ▸ Check for Updates… reads (the in-app updater, crates/updater): the version, the + # release notes and, per platform, the file to download and its SHA-256. Published on every + # release — prereleases included, marked as such; the app only offers one to someone who + # ticked "Include prereleases" — it is a plain file on the release, so the check keeps + # working when GitHub's API is rate-limited. It is built after the release exists so the + # notes are the published ones ("What's New" in the dialog). + env: + DISPLAY_NAME: ${{ needs.version.outputs.display_name }} + REPO: ${{ github.repository }} + run: | + tag="v$VERSION" + # a manifest left over from a previous run of this draft must not describe this one + rm -f latest.json latest.json.new + notes="$(gh release view "$tag" --json body --jq .body)" + # the asset names are the artifacts' file names (what the app matches against) + jq -n --arg version "$VERSION" --arg name "$DISPLAY_NAME v$VERSION" \ + --arg date "$(date -u +%Y-%m-%dT%H:%M:%SZ)" \ + --arg tag "$tag" --arg repo "$REPO" --arg notes "$notes" \ + --argjson pre "$PRERELEASE" '{ + version: $version, + name: $name, + pub_date: $date, + notes: $notes, + releases: [{ + tag: $tag, + name: $name, + notes: $notes, + date: $date, + prerelease: $pre, + assets: [] + }] + }' > latest.json + # every artifact but the checksum list becomes an asset, with its size and SHA-256 + for f in *; do + case "$f" in SHA256SUMS.txt|latest.json) continue ;; esac + [ -f "$f" ] || continue + sha="$(awk -v name="$f" '$2 == name || $2 == "*" name { print $1; exit }' SHA256SUMS.txt)" + [ -n "$sha" ] || { echo "::error::no checksum for $f"; exit 1; } + size="$(stat -c %s "$f")" + jq --arg name "$f" --arg url "https://github.com/$REPO/releases/download/$tag/$f" \ + --arg sha "$sha" --argjson size "$size" \ + '.releases[0].assets += [{name: $name, url: $url, size: $size, sha256: $sha}]' \ + latest.json > latest.json.new + mv latest.json.new latest.json + done + jq -e '.version != "" and (.releases[0].assets | length) > 0' latest.json >/dev/null + rm -f latest.json.new + gh release upload "$tag" --clobber latest.json + jq -r '.releases[0].assets[] | "\(.name) \(.size) \(.sha256)"' latest.json diff --git a/Cargo.lock b/Cargo.lock index edb3ffadd1..599d8b2ee4 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4661,6 +4661,7 @@ dependencies = [ "lcc-segment", "lcc-tether", "lcc-tiff", + "lcc-updater", "lcc-video", "lcc-video-export", "lcc-webgallery", @@ -4672,6 +4673,7 @@ dependencies = [ "rustix 1.1.5", "serde", "serde_json", + "sha2 0.10.9", "thiserror 2.0.21", "tiff", "unicode-segmentation", @@ -5147,6 +5149,7 @@ dependencies = [ "lcc-raster", "lcc-slideshow", "lcc-text", + "lcc-updater", "lcc-webgallery", "log", "resvg", @@ -5157,6 +5160,17 @@ dependencies = [ "web-time", ] +[[package]] +name = "lcc-updater" +version = "0.7.0" +dependencies = [ + "lcc-brand", + "lcc-net", + "log", + "serde_json", + "sha2 0.10.9", +] + [[package]] name = "lcc-video" version = "0.7.0" diff --git a/Cargo.toml b/Cargo.toml index 76f3f3c7dd..16a2b35a40 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -41,6 +41,7 @@ lcc-ui-egui = { path = "crates/ui-egui" } lcc-mcp = { path = "crates/mcp" } lcc-fetch = { path = "crates/fetch" } lcc-net = { path = "crates/net" } +lcc-updater = { path = "crates/updater" } lcc-credentials = { path = "crates/credentials" } lcc-hash = { path = "crates/hash" } lcc-fuzzkit = { path = "crates/fuzzkit" } diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index c40bfdccaa..24b879e513 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -55,6 +55,8 @@ lcc-audio-out = { workspace = true } # model downloads run natively only (the web build fetches no models) [target.'cfg(not(target_arch = "wasm32"))'.dependencies] lcc-fetch = { workspace = true } +# auto updates: the release feed, the download, and starting the install +lcc-updater = { workspace = true } lcc-immich = { workspace = true } lcc-publish = { workspace = true } lcc-tether = { workspace = true } @@ -80,6 +82,8 @@ rawnind-model = ["denoise", "lcc-denoise/rawnind-model", "lcc-denoise-core/rawni [dev-dependencies] # HDR JPEG XL tests read the file's colour encoding jxl-oxide = { workspace = true } +# the updater's end-to-end test builds a release with a real checksum +sha2 = { workspace = true } # Lossless synthetic HEIC files (the import test; decoded when the codecs' `heif` feature is on). lcc-heif = { workspace = true, features = ["testdata"] } libc = { workspace = true } diff --git a/crates/engine/src/cmd/mod.rs b/crates/engine/src/cmd/mod.rs index d2d0746861..f5d0ae6505 100644 --- a/crates/engine/src/cmd/mod.rs +++ b/crates/engine/src/cmd/mod.rs @@ -60,6 +60,8 @@ mod quick; mod sync; #[cfg(not(target_arch = "wasm32"))] pub mod tether; +#[cfg(not(target_arch = "wasm32"))] +pub mod update; pub mod video; #[cfg(not(target_arch = "wasm32"))] pub mod web; @@ -244,6 +246,8 @@ pub fn command_specs() -> &'static [CommandSpec] { v.extend(edit_in::specs()); #[cfg(not(target_arch = "wasm32"))] v.extend(plugins::specs()); + #[cfg(not(target_arch = "wasm32"))] + v.extend(update::specs()); v.extend(activity::specs()); v.extend(video::specs()); v diff --git a/crates/engine/src/cmd/update.rs b/crates/engine/src/cmd/update.rs new file mode 100644 index 0000000000..6b0abdb42c --- /dev/null +++ b/crates/engine/src/cmd/update.rs @@ -0,0 +1,334 @@ +//! Auto updates as commands: check the release feed, download what it offers, install it, and the +//! two settings that decide when all that happens ([`crate::update`]). +//! +//! The UI (Help ▸ Check for Updates…), the CLI and the control channel all dispatch these by id, so +//! an agent can drive an update exactly the way the dialog does. + +use serde_json::{Value, json}; + +use super::{CommandSpec, always, bad, cmd}; +use crate::update::{self, Kind, Progress, Staged}; +use crate::{Result, Session}; + +fn status(s: &mut Session, _: &Value) -> Result { + Ok(s.updater.status()) +} + +/// `update.check [wait, feed]`: start a check (background), or run it here and answer with the +/// outcome. `feed` reads another URL instead (a mirror, a local feed); it lasts for this session. +fn check(s: &mut Session, p: &Value) -> Result { + const C: &str = "update.check"; + if let Some(feed) = p.get("feed") { + match feed { + Value::Null | Value::String(_) => { + let url = feed.as_str().map(str::to_string); + if url.as_ref().is_some_and(|u| u.len() > 2_000) { + return Err(bad(C, "feed is at most 2000 characters")); + } + s.updater.set_manifest_url(url); + } + _ => return Err(bad(C, "feed must be a URL or null (the project's own feed)")), + } + } + let wait = p.get("wait").and_then(Value::as_bool).unwrap_or(false); + if wait && !s.updater.checking() { + s.updater.check_now(); + } else if !s.updater.start_check() && !s.updater.checking() { + return Err(bad(C, "a check could not be started; try again")); + } + if wait { + s.updater.wait_for_check(); + } + Ok(s.updater.status()) +} + +/// `update.download [wait]`: fetch the file the check offered. +fn download(s: &mut Session, p: &Value) -> Result { + const C: &str = "update.download"; + let activity = s.activity.clone(); + s.updater.start_download(&activity).map_err(|e| bad(C, e))?; + if p.get("wait").and_then(Value::as_bool) == Some(true) { + s.updater.wait_for_download(); + if let Progress::Failed(why) = s.updater.progress() { + return Err(bad(C, why.clone())); + } + } + Ok(s.updater.status()) +} + +fn cancel_download(s: &mut Session, _: &Value) -> Result { + Ok(json!({"cancelled": s.updater.cancel_download()})) +} + +/// `update.install [confirm]`: apply the downloaded file. Without `confirm` it answers with what +/// installing would do (the dialog shows that first). +fn install(s: &mut Session, p: &Value) -> Result { + const C: &str = "update.install"; + let Some(staged) = s.updater.staged().cloned() else { + return Err(bad(C, "no update has been downloaded: run update.check then update.download")); + }; + if staged.kind == Kind::Checksums { + return Err(bad(C, "that release offers no file for this system")); + } + let plan = update::plan(&staged); + if p.get("confirm").and_then(Value::as_bool) != Some(true) { + return Ok(json!({ + "version": staged.version, + "summary": plan.summary, + "steps": plan.steps, + "destination": plan.destination.map(|d| d.to_string_lossy().to_string()), + "restart": restart_text(plan.restart), + "file": staged.file, + "bytes": staged.bytes, + "sha256": staged.sha256, + })); + } + let installed = update::install(&staged).map_err(|e| bad(C, e))?; + let exit = installed.exit; + let out = json!({"version": installed.version, "message": installed.message, "exit": exit}); + s.updater.set_installed(installed); + Ok(out) +} + +fn restart_text(restart: lcc_updater::Restart) -> &'static str { + match restart { + lcc_updater::Restart::QuitAndRelaunch => "quitAndRelaunch", + lcc_updater::Restart::QuitOnly => "quit", + lcc_updater::Restart::Manual => "manual", + } +} + +/// `update.discard`: delete the downloaded file. +fn discard(s: &mut Session, _: &Value) -> Result { + match s.updater.staged().cloned() { + Some(staged) => { + update::discard(&staged); + s.updater.clear_installed(); + Ok(s.updater.status()) + } + None => Err(bad("update.discard", "no update has been downloaded")), + } +} + +/// `update.prefs`: the two settings, and whether they are remembered between runs. +fn prefs(s: &mut Session, p: &Value) -> Result { + const C: &str = "update.prefs"; + let flag = |key: &str| -> Result> { + match p.get(key) { + None | Some(Value::Null) => Ok(None), + Some(Value::Bool(v)) => Ok(Some(*v)), + Some(_) => Err(bad(C, format!("{key} must be true or false"))), + } + }; + let check_at_startup = flag("checkAtStartup")?; + let prerelease = flag("prerelease")?; + if check_at_startup.is_some() || prerelease.is_some() { + s.updater.set_prefs(check_at_startup, prerelease); + } + let mut v = s.updater.status(); + v["persistent"] = json!(s.updater.persistent()); + v["staging"] = json!(s.updater.stage_dir().to_string_lossy()); + Ok(v) +} + +/// `update.dismiss`: the user was told about `version` and does not want to be told again. +fn dismiss(s: &mut Session, p: &Value) -> Result { + const C: &str = "update.dismiss"; + let version = match p.get("version").and_then(Value::as_str) { + Some(v) if !v.is_empty() && v.len() <= 64 => v.to_string(), + _ => match s.updater.available() { + Some(a) => a.version.clone(), + None => return Err(bad(C, "no version to dismiss")), + }, + }; + let skipped = p.get("skipped").and_then(Value::as_bool).unwrap_or(true); + s.updater.mark_seen(&version, skipped); + Ok(s.updater.status()) +} + +/// The staged file, for a caller that wants to know where it is. +pub fn staged_of(s: &Session) -> Option { + s.updater.staged().cloned() +} + +pub fn specs() -> Vec { + vec![ + cmd!( + query "update.status", + "Update Status", + [], + None, + "{} → {version, platform, supported, check: never | running | current | found, download: idle | running | ready | failed | cancelled, checkAtStartup, prerelease, lastChecked, seenVersion, repo, page, staging, available?: {version, current, title, tag, published, notes, file, size, action, verified, kind}, progress?: {bytes, total}, staged?: {version, file, bytes, sha256, path, kind}, installed?: {version, message, exit}, error?} — what the updater knows right now", + always, + status + ), + cmd!( + query "update.check", + "Check for Updates", + [], + None, + "{wait?: bool, feed?: url|null} — read the release feed in the background and compare it with this build (one request; a recent answer is reused). `feed` reads another URL instead of the project's own (a mirror, a fork, a local feed) for the rest of the session; null goes back to the default (also `{env}_UPDATE_URL` at start-up). `wait: true` runs it now and answers with the outcome, for one-shot callers → status", + always, + check + ), + cmd!( + query "update.download", + "Download Update", + [], + None, + "{wait?: bool} — fetch the file the check offered for this system into the cache folder (resumable, size- and SHA-256-checked; the activity stack shows it and can cancel it). `wait: true` blocks until it is in, for one-shot callers → status", + always, + download + ), + cmd!( + query "update.downloadCancel", + "Cancel Update Download", + [], + None, + "{} → {cancelled} — stop the transfer; nothing is left behind", + always, + cancel_download + ), + cmd!( + query "update.install", + "Install Update", + [], + None, + "{confirm?: bool} — without `confirm`: what installing the downloaded file would do ({summary, steps, destination, restart: quitAndRelaunch | quit | manual}). With `confirm: true`: do it — run the installer, replace the AppImage, or open the file's folder — and say whether the app has to quit ({message, exit})", + always, + install + ), + cmd!( + query "update.discard", + "Discard Downloaded Update", + [], + None, + "{} — delete the downloaded file → status", + always, + discard + ), + cmd!( + query "update.prefs", + "Update Preferences", + [], + None, + "{checkAtStartup?: bool, prerelease?: bool} — ask the feed when the app starts, and whether prereleases count as updates (saved in the app's own settings folder, `updates.json`; a session opened without a library keeps them in memory only) → status + {persistent, staging}", + always, + prefs + ), + cmd!( + query "update.dismiss", + "Dismiss Update", + [], + None, + "{version?, skipped?: bool} — remember that the user answered about this version, so a start-up check does not ask again (defaults to the version on offer) → status", + always, + dismiss + ), + ] +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::Session; + + fn session() -> Session { + // in-memory only: no settings file, no library, no network + let mut s = Session::new(); + s.updater = crate::update::Updater::new(None); + s + } + + #[test] + fn the_status_lists_everything_a_dialog_needs() { + let mut s = session(); + let v = s.execute("update.status", &json!({})).expect("status"); + assert_eq!(v["version"], env!("CARGO_PKG_VERSION")); + assert!(v["platform"].as_str().is_some_and(|p| p.contains('-'))); + assert_eq!(v["check"], "never"); + assert_eq!(v["checkAtStartup"], true); + assert_eq!(v["prerelease"], false); + assert!(v["page"].as_str().is_some_and(|p| p.ends_with("/releases"))); + } + + #[test] + fn installing_without_a_download_is_an_error() { + let mut s = session(); + let err = s.execute("update.install", &json!({"confirm": true})).expect_err("nothing staged"); + assert!(err.to_string().contains("update.download"), "{err}"); + let err = s.execute("update.discard", &json!({})).expect_err("nothing staged"); + assert!(err.to_string().contains("no update"), "{err}"); + } + + #[test] + fn a_download_without_an_update_is_an_error() { + let mut s = session(); + let err = s.execute("update.download", &json!({})).expect_err("nothing on offer"); + assert!(err.to_string().contains("check"), "{err}"); + } + + #[test] + fn the_settings_round_trip_and_are_validated() { + let mut s = session(); + let v = s.execute("update.prefs", &json!({"checkAtStartup": false, "prerelease": true})).expect("prefs"); + assert_eq!((v["checkAtStartup"].as_bool(), v["prerelease"].as_bool()), (Some(false), Some(true))); + assert_eq!(v["persistent"], false, "an in-memory session remembers nothing"); + let err = s.execute("update.prefs", &json!({"prerelease": "yes"})).expect_err("not a bool"); + assert!(err.to_string().contains("true or false"), "{err}"); + } + + #[test] + fn dismissing_remembers_the_version() { + let mut s = session(); + s.updater.apply(lcc_updater::Checked::Found(Box::new(lcc_updater::Update { + current: lcc_updater::Version::parse("1.0.0").expect("v"), + version: lcc_updater::Version::parse("1.2.0").expect("v"), + title: "App 1.2.0".into(), + tag: "v1.2.0".into(), + asset: lcc_updater::Asset { + name: "app-1.2.0-windows-x64.msi".into(), + url: "https://example.invalid/a.msi".into(), + size: 10, + sha256: None, + kind: lcc_updater::Kind::Msi, + }, + sha256: None, + published: None, + notes: String::new(), + action: "install".into(), + }))); + assert!(s.updater.available().is_some()); + let v = s.execute("update.dismiss", &json!({})).expect("dismiss"); + assert_eq!(v["seenVersion"]["version"], "1.2.0"); + assert_eq!(v["seenVersion"]["skipped"], true); + // and no update on offer: dismissing with nothing to dismiss is an error + let mut fresh = session(); + assert!(fresh.execute("update.dismiss", &json!({})).is_err()); + } + + #[test] + fn the_install_plan_is_available_before_confirming() { + let mut s = session(); + let dir = std::env::temp_dir().join(format!("lcc-cmd-update-{}", std::process::id())); + let _ = std::fs::create_dir_all(&dir); + let file = dir.join("app-1.2.0-windows-x64.msi"); + std::fs::write(&file, b"installer").expect("write"); + s.updater.set_progress(Progress::Ready(Box::new(Staged { + version: "1.2.0".into(), + path: file, + bytes: 9, + sha256: "ab".repeat(32), + file: "app-1.2.0-windows-x64.msi".into(), + kind: Kind::Msi, + notes: String::new(), + }))); + let v = s.execute("update.install", &json!({})).expect("plan"); + assert_eq!(v["version"], "1.2.0"); + assert!(v["summary"].as_str().is_some_and(|t| t.contains("installer")), "{v}"); + assert!(v["steps"].as_array().is_some_and(|a| !a.is_empty())); + assert_eq!(v["file"], "app-1.2.0-windows-x64.msi"); + assert_eq!(v["sha256"], "ab".repeat(32)); + let _ = std::fs::remove_dir_all(&dir); + } +} diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index eb03d38733..4513d2ebf9 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -71,6 +71,8 @@ pub mod sidecar; pub mod smart; pub mod sync; pub mod timelapse; +#[cfg(not(target_arch = "wasm32"))] +pub mod update; pub mod video; mod view; pub mod walk; @@ -230,6 +232,9 @@ pub struct Session { /// Remote services: SHA-1 back-fill and Immich jobs ([`remote`]). #[cfg(not(target_arch = "wasm32"))] pub remote: remote::State, + /// Auto updates: the last check, the download in flight, and the settings ([`update`]). + #[cfg(not(target_arch = "wasm32"))] + pub updater: update::Updater, /// Copied develop settings (partial JSON) for Paste. pub clipboard: Option, /// The folder on disk the [`LibrarySource::Folder`] view browses. @@ -391,6 +396,8 @@ impl Session { faces: Default::default(), #[cfg(not(target_arch = "wasm32"))] remote: Default::default(), + #[cfg(not(target_arch = "wasm32"))] + updater: Default::default(), clipboard: None, meta_clipboard: None, browse: None, diff --git a/crates/engine/src/update.rs b/crates/engine/src/update.rs new file mode 100644 index 0000000000..593be277a2 --- /dev/null +++ b/crates/engine/src/update.rs @@ -0,0 +1,810 @@ +//! Auto updates: checking the release feed, downloading the file for this machine, and starting +//! the install ([`lcc_updater`]). +//! +//! A check runs on a worker thread — the UI never waits for the network — and its result stays in +//! [`Check`] until the next one. A download shows in the activity stack (kind `update`, +//! cancellable) and, once it has arrived and checked out, waits in the cache folder until the user +//! says *Install and Relaunch*. Everything that can go wrong is a sentence in the status or the +//! command's error, never a panic, and a failed update leaves the running installation alone. +//! +//! Settings (check at startup, include prereleases) live in the app's own settings folder +//! (`updates.json`), not the library's: there is one installation per machine, and the updater +//! works with no library open. + +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::mpsc::{Receiver, TryRecvError}; +use std::sync::{Arc, Mutex, PoisonError}; + +use serde::{Deserialize, Serialize}; +use serde_json::{Value, json}; + +use crate::activity::{Activity, Cancel, Unit}; + +/// The `kind` of the download's activity row. +pub const ACTIVITY_KIND: &str = "update"; +/// The row's label (English; the frontend translates it). +pub const ACTIVITY_LABEL: &str = "Downloading update"; + +/// Settings file in the app's settings folder. +const SETTINGS_FILE: &str = "updates.json"; +/// Schema version of that file; a file from a newer build is left alone. +const SETTINGS_VERSION: u32 = 1; + +/// What the user chose about updates (persisted in `updates.json`). +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(default, rename_all = "camelCase")] +pub struct Prefs { + /// Ask the release feed once when the app starts. + pub check_at_startup: bool, + /// Treat prereleases (`1.2.0-rc.1`) as updates. + pub prerelease: bool, + /// The last version the user answered about, so a start-up check does not ask twice. + pub seen_version: Option, +} + +impl Default for Prefs { + fn default() -> Self { + Prefs { check_at_startup: true, prerelease: false, seen_version: None } + } +} + +/// The last version the user was shown. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct SeenVersion { + pub version: String, + pub skipped: bool, +} + +#[derive(Default, Serialize, Deserialize)] +#[serde(default, rename_all = "camelCase")] +struct SettingsFile { + version: u32, + updates: Prefs, +} + +/// How a downloaded update is installed. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Kind { + Msi, + Dmg, + AppImage, + Archive, + Checksums, +} + +impl Kind { + pub fn text(self) -> &'static str { + match self { + Kind::Msi => "msi", + Kind::Dmg => "dmg", + Kind::AppImage => "appimage", + Kind::Archive => "archive", + Kind::Checksums => "checksums", + } + } + + fn of(kind: lcc_updater::Kind) -> Kind { + match kind { + lcc_updater::Kind::Msi => Kind::Msi, + lcc_updater::Kind::Dmg => Kind::Dmg, + lcc_updater::Kind::AppImage => Kind::AppImage, + lcc_updater::Kind::Archive => Kind::Archive, + lcc_updater::Kind::Checksums => Kind::Checksums, + } + } + + fn to_crate(self) -> lcc_updater::Kind { + match self { + Kind::Msi => lcc_updater::Kind::Msi, + Kind::Dmg => lcc_updater::Kind::Dmg, + Kind::AppImage => lcc_updater::Kind::AppImage, + Kind::Archive => lcc_updater::Kind::Archive, + Kind::Checksums => lcc_updater::Kind::Checksums, + } + } +} + +/// A newer release the feed offered. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Available { + pub version: String, + pub current: String, + pub title: String, + pub tag: String, + pub published: Option, + pub notes: String, + /// The file's name, as the release spells it. + pub file: String, + /// Bytes, when the feed says (0: unknown). + pub size: u64, + /// One line on what installing it will do on this machine. + pub action: String, + /// The install kind. + pub kind: Kind, + /// Where it downloads from. Not shown in the status: it is long, and the dialog shows the file. + pub url: String, + /// The SHA-256 to check it against, when the release publishes one. + pub sha256: Option, +} + +impl Available { + fn of(u: &lcc_updater::Update) -> Available { + Available { + version: u.version.to_text(), + current: u.current.to_text(), + title: u.title.clone(), + tag: u.tag.clone(), + published: u.published.clone(), + notes: u.notes.clone(), + file: u.asset.name.clone(), + size: u.asset.size, + action: u.action.clone(), + kind: Kind::of(u.asset.kind), + url: u.asset.url.clone(), + sha256: u.sha256.clone(), + } + } + + /// The update as the downloader needs it. + fn to_crate(&self) -> lcc_updater::Update { + lcc_updater::Update { + current: parse_or_current(&self.current), + version: parse_or_current(&self.version), + title: self.title.clone(), + tag: self.tag.clone(), + asset: lcc_updater::Asset { + name: self.file.clone(), + url: self.url.clone(), + size: self.size, + sha256: self.sha256.clone(), + kind: self.kind.to_crate(), + }, + sha256: self.sha256.clone(), + published: self.published.clone(), + notes: self.notes.clone(), + action: self.action.clone(), + } + } +} + +fn parse_or_current(text: &str) -> lcc_updater::Version { + lcc_updater::Version::parse(text).unwrap_or_else(|_| lcc_updater::Version::current()) +} + +/// A finished download, waiting to be installed. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Staged { + pub version: String, + pub path: PathBuf, + pub bytes: u64, + /// Lower-case hex SHA-256 of the file as it was written. + pub sha256: String, + pub file: String, + pub kind: Kind, + /// The release notes, kept with the file so the dialog still has them. + pub notes: String, +} + +/// What the last check found. +#[derive(Clone, Debug, PartialEq, Eq, Default)] +pub enum Check { + /// No check has run yet, or the last one failed. + #[default] + Never, + /// One is running on a worker thread. + Running, + /// This build is the newest the feed knows of. + Current, + /// A newer release is available. + Found(Box), +} + +/// Where the download of the newest release stands. +#[derive(Clone, Debug, PartialEq, Eq, Default)] +pub enum Progress { + #[default] + Idle, + /// Fetching `bytes` of `total` (`total` 0 while the size is unknown). + Running { bytes: u64, total: u64 }, + /// Arrived and checked; waiting for *Install and Relaunch*. + Ready(Box), + /// The transfer failed (the user can try again). + Failed(String), + /// The user cancelled it. + Cancelled, +} + +/// What an install left behind. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Installed { + pub version: String, + pub message: String, + /// Whether the app has to quit for the install to finish. + pub exit: bool, +} + +/// A download in flight: its progress and the flag that stops it. +/// +/// The activity row belongs to the worker thread (`TaskGuard` is not `Sync`, and the row should go +/// when the transfer ends, however it ends), so nothing here holds a task handle. +struct Job { + progress: Arc>, + cancel: Arc, +} + +fn lock(m: &Mutex) -> std::sync::MutexGuard<'_, T> { + m.lock().unwrap_or_else(PoisonError::into_inner) +} + +/// The updater's state in one session. +pub struct Updater { + prefs: Prefs, + /// Where `updates.json` lives (`None`: an in-memory session; the settings are not written). + dir: Option, + /// A feed URL that replaces the release's own (`_UPDATE_URL` puts one here). + manifest_url: Option, + /// Where downloads are staged. + stage: PathBuf, + cache: lcc_updater::Cache, + check: Check, + progress: Progress, + installed: Option, + /// When the last check finished (ISO 8601). + checked_at: Option, + /// How a running check reports back. + worker: Option>, + /// Why the last check or download failed, in words. + error: Option, + /// The download in flight. + job: Option, +} + +impl Default for Updater { + /// The updater a new session gets: settings in the app's own folder, downloads beside them. + fn default() -> Self { + Updater::with_default_dir() + } +} + +impl Updater { + /// An updater with no settings folder of its own. + pub fn new(dir: Option) -> Updater { + let prefs = dir.as_deref().map(load_prefs).unwrap_or_default(); + let stage = match &dir { + Some(d) => lcc_updater::stage_dir(d), + None => std::env::temp_dir().join(format!("{}-updates", lcc_brand::BINARY)), + }; + Updater { + prefs, + dir, + manifest_url: None, + stage, + cache: lcc_updater::Cache::default(), + check: Check::Never, + progress: Progress::Idle, + installed: None, + checked_at: None, + worker: None, + error: None, + job: None, + } + } + + /// [`Updater::new`] at the app's settings folder, downloads staged in its `updates` folder. + pub fn with_default_dir() -> Updater { + Updater::new(crate::config::config_dir()) + } + + /// Where downloads are staged. + pub fn stage_dir(&self) -> &Path { + &self.stage + } + + /// Whether the settings are remembered between runs. + pub fn persistent(&self) -> bool { + self.dir.is_some() + } + + // ---------- settings + + pub fn prefs(&self) -> &Prefs { + &self.prefs + } + + /// Change the settings; `true` when something changed (and was written). + pub fn set_prefs(&mut self, check_at_startup: Option, prerelease: Option) -> bool { + let before = self.prefs.clone(); + if let Some(v) = check_at_startup { + self.prefs.check_at_startup = v; + } + if let Some(v) = prerelease { + self.prefs.prerelease = v; + } + if self.prefs == before { + return false; + } + self.save(); + true + } + + /// Remember which version the user answered about, so the next start-up check stays quiet + /// about it. + pub fn mark_seen(&mut self, version: &str, skipped: bool) { + self.prefs.seen_version = Some(SeenVersion { version: version.to_string(), skipped }); + self.save(); + } + + /// Whether the user has already been shown `version`. + pub fn already_seen(&self, version: &str) -> bool { + self.prefs.seen_version.as_ref().is_some_and(|s| s.version == version) + } + + fn save(&self) { + let Some(dir) = &self.dir else { return }; + let file = SettingsFile { version: SETTINGS_VERSION, updates: self.prefs.clone() }; + let Ok(text) = serde_json::to_vec_pretty(&file) else { + log::warn!("updates: could not write the settings"); + return; + }; + if let Err(e) = std::fs::create_dir_all(dir) { + log::warn!("updates: {}: {e}", dir.display()); + return; + } + // written beside and renamed: a crash mid-write cannot leave a half file behind + let path = dir.join(SETTINGS_FILE); + let part = dir.join(format!("{SETTINGS_FILE}.part")); + match std::fs::write(&part, &text).and_then(|()| std::fs::rename(&part, &path)) { + Ok(()) => {} + Err(e) => { + let _ = std::fs::remove_file(&part); + log::warn!("updates: {}: {e}", path.display()); + } + } + } + + // ---------- state + + pub fn check(&self) -> &Check { + &self.check + } + + pub fn progress(&self) -> &Progress { + &self.progress + } + + pub fn installed(&self) -> Option<&Installed> { + self.installed.as_ref() + } + + /// Forget the *Install and Relaunch* outcome (the dialog says it once). + pub fn clear_installed(&mut self) { + self.installed = None; + } + + /// Whether a check is in flight. + pub fn checking(&self) -> bool { + matches!(self.check, Check::Running) + } + + /// Whether a download is in flight. + pub fn downloading(&self) -> bool { + matches!(self.progress, Progress::Running { .. }) + } + + /// The newer release on offer, when there is one. + pub fn available(&self) -> Option<&Available> { + match &self.check { + Check::Found(a) => Some(a), + _ => None, + } + } + + /// The downloaded file waiting to be installed, when there is one. + pub fn staged(&self) -> Option<&Staged> { + match &self.progress { + Progress::Ready(s) => Some(s), + _ => None, + } + } + + /// Everything about updates a frontend shows (`update.status`). + pub fn status(&self) -> Value { + let mut v = json!({ + "version": env!("CARGO_PKG_VERSION"), + "platform": platform_text(), + "supported": platform_supported(), + "check": match &self.check { + Check::Never => "never", + Check::Running => "running", + Check::Current => "current", + Check::Found(_) => "found", + }, + "download": match &self.progress { + Progress::Idle => "idle", + Progress::Running { .. } => "running", + Progress::Ready(_) => "ready", + Progress::Failed(_) => "failed", + Progress::Cancelled => "cancelled", + }, + "checkAtStartup": self.prefs.check_at_startup, + "prerelease": self.prefs.prerelease, + "lastChecked": self.checked_at, + "seenVersion": self.prefs.seen_version.as_ref().map(|s| json!({"version": s.version, "skipped": s.skipped})), + "repo": lcc_brand::REPOSITORY, + "page": format!("{}/releases", lcc_brand::REPOSITORY), + "staging": self.stage.to_string_lossy(), + }); + if let Check::Found(a) = &self.check { + v["available"] = available_json(a); + } + match &self.progress { + Progress::Running { bytes, total } => v["progress"] = json!({"bytes": bytes, "total": total}), + Progress::Ready(s) => v["staged"] = staged_json(s), + Progress::Failed(why) => v["error"] = json!(why), + _ => {} + } + if let Some(e) = &self.error { + v["error"] = json!(e); + } + if let Some(i) = &self.installed { + v["installed"] = json!({"version": i.version, "message": i.message, "exit": i.exit}); + } + v + } + + // ---------- checking + + /// The options a check runs with (the user's prerelease choice included, and the feed override + /// when one is set). + pub fn options(&self) -> lcc_updater::Options { + lcc_updater::Options { prerelease: self.prefs.prerelease, manifest_url: self.manifest_url.clone(), ..Default::default() } + } + + /// Read the release feed from `url` instead of the project's (`_UPDATE_URL` sets this + /// at start-up; a mirror, a fork or a test feed). `None` goes back to the default. + pub fn set_manifest_url(&mut self, url: Option) { + self.manifest_url = url.map(|u| u.trim().to_string()).filter(|u| !u.is_empty()); + } + + /// The feed URL in use (`None`: the project's own). + pub fn manifest_url(&self) -> Option<&str> { + self.manifest_url.as_deref() + } + + /// Start a check on a worker thread. `false` when one is already running. + pub fn start_check(&mut self) -> bool { + if self.checking() { + return false; + } + let opts = self.options(); + // an answer from the last few seconds costs no request + if let Some(cached) = self.cache.get(&opts) { + self.apply(cached); + return true; + } + if !self.cache.begin() { + return false; + } + self.check = Check::Running; + self.error = None; + let (tx, rx) = std::sync::mpsc::channel(); + let spawned = std::thread::Builder::new().name("lc-update-check".into()).spawn(move || { + let checked = match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| lcc_updater::check(&opts, None, None))) { + Ok(Ok(Some(u))) => lcc_updater::Checked::Found(Box::new(u)), + Ok(Ok(None)) => lcc_updater::Checked::Current(env!("CARGO_PKG_VERSION").to_string()), + Ok(Err(e)) => lcc_updater::Checked::Failed(e.to_string()), + Err(_) => lcc_updater::Checked::Failed("the check stopped unexpectedly".into()), + }; + // the receiver is gone when the session ended first: nothing to report, no panic + let _ = tx.send(checked); + }); + match spawned { + Ok(_) => { + self.worker = Some(rx); + true + } + Err(e) => { + self.check = Check::Never; + self.error = Some(format!("could not start the check: {e}")); + self.cache.end(); + false + } + } + } + + /// Run a check in this thread (a one-shot caller: the CLI, or `wait: true`). + pub fn check_now(&mut self) { + let opts = self.options(); + let checked = match lcc_updater::check(&opts, None, None) { + Ok(Some(u)) => lcc_updater::Checked::Found(Box::new(u)), + Ok(None) => lcc_updater::Checked::Current(env!("CARGO_PKG_VERSION").to_string()), + Err(e) => lcc_updater::Checked::Failed(e.to_string()), + }; + self.apply(checked); + } + + /// Take a finished check's or download's result. `true` when something changed. + pub fn poll(&mut self) -> bool { + let mut changed = false; + let got = match self.worker.as_ref().map(Receiver::try_recv) { + Some(Ok(checked)) => Some(checked), + Some(Err(TryRecvError::Disconnected)) => Some(lcc_updater::Checked::Failed("the check stopped unexpectedly".into())), + // still running, or no check at all + _ => None, + }; + if let Some(checked) = got { + self.worker = None; + self.apply(checked); + changed = true; + } + if let (Some(job), Progress::Running { .. }) = (&self.job, &self.progress) { + let now = lock(&job.progress).clone(); + if now != self.progress { + self.progress = now; + changed = true; + } + if matches!(self.progress, Progress::Ready(_) | Progress::Failed(_) | Progress::Cancelled) { + self.job = None; + changed = true; + } + } + changed + } + + /// Wait for a running check to finish (blocking; a one-shot caller asks for this). + pub fn wait_for_check(&mut self) { + while self.checking() { + if !self.poll() { + std::thread::sleep(std::time::Duration::from_millis(20)); + } + } + } + + /// Wait for a running download to finish (blocking). + pub fn wait_for_download(&mut self) { + while self.downloading() { + if !self.poll() { + std::thread::sleep(std::time::Duration::from_millis(50)); + } + } + } + + /// Record what a check found. + pub fn apply(&mut self, checked: lcc_updater::Checked) { + self.checked_at = Some(iso_now()); + self.cache.put(&self.options(), checked.clone()); + self.check = match checked { + lcc_updater::Checked::Found(u) => Check::Found(Box::new(Available::of(&u))), + lcc_updater::Checked::Current(_) => Check::Current, + lcc_updater::Checked::Failed(why) => { + log::info!("updates: {why}"); + self.error = Some(why); + // a failed check says nothing about this build: the next one may succeed + Check::Never + } + }; + self.cache.end(); + // a newer release replaces a file staged for an older one + if let (Some(a), Progress::Ready(s)) = (self.available(), &self.progress) + && s.version != a.version + { + self.progress = Progress::Idle; + } + } + + // ---------- downloading + + /// Start fetching the offered release. `Err` says why it cannot start. + pub fn start_download(&mut self, activity: &Activity) -> Result<(), String> { + if self.downloading() { + return Err("an update is already downloading".into()); + } + let available = self.available().cloned().ok_or("there is no update to download: check again first")?; + if available.kind == Kind::Checksums { + return Err("that release offers no file for this system".into()); + } + if let Err(e) = std::fs::create_dir_all(&self.stage) { + return Err(format!("could not create {}: {e}", self.stage.display())); + } + self.error = None; + self.progress = Progress::Running { bytes: 0, total: available.size }; + let progress = Arc::new(Mutex::new(self.progress.clone())); + let cancel = Arc::new(AtomicBool::new(false)); + let task = activity.start(ACTIVITY_KIND, ACTIVITY_LABEL, Cancel::Flag(cancel.clone())); + task.set_unit(Unit::Bytes); + task.detail(&available.file); + task.progress(0, available.size); + // progress from the worker does not keep the row alive; the guard below does + let handle = task.handle(); + let stage = self.stage.clone(); + let update = available.to_crate(); + let worker_progress = progress.clone(); + let worker_cancel = cancel.clone(); + let spawned = std::thread::Builder::new().name("lc-update-download".into()).spawn(move || { + // the activity row lives exactly as long as the transfer + let _task = task; + let outcome = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + let client = lcc_updater::client().map_err(|e| e.to_string())?; + let mut report = |bytes: u64, total: Option| { + let total = total.unwrap_or(update.asset.size); + *lock(&worker_progress) = Progress::Running { bytes, total }; + handle.progress(bytes, total); + }; + let got = + lcc_updater::download(&update, &client, &stage, Some(worker_cancel.clone()), Some(&mut report)).map_err(|e| e.to_string())?; + Ok::<_, String>(Staged { + version: update.version.to_text(), + path: got.path, + bytes: got.bytes, + sha256: got.sha256, + file: got.name, + kind: Kind::of(update.asset.kind), + notes: update.notes.clone(), + }) + })); + let end = match outcome { + Ok(Ok(staged)) => Progress::Ready(Box::new(staged)), + // a cancelled transfer reports the failure the net layer saw; the flag says which + Ok(Err(_)) if worker_cancel.load(Ordering::Relaxed) => Progress::Cancelled, + Ok(Err(why)) => Progress::Failed(why), + Err(_) => Progress::Failed("the download stopped unexpectedly".into()), + }; + *lock(&worker_progress) = end; + // the caller takes the result on its next poll + }); + match spawned { + Ok(_) => { + self.job = Some(Job { progress, cancel }); + Ok(()) + } + Err(e) => { + self.progress = Progress::Failed(format!("could not start the download: {e}")); + Err(format!("could not start the download: {e}")) + } + } + } + + /// Stop a running download: the transfer notices and leaves nothing behind. + pub fn cancel_download(&mut self) -> bool { + match &self.job { + Some(job) => { + job.cancel.store(true, Ordering::Relaxed); + true + } + None => false, + } + } + + /// Remember how an install ended. + pub fn set_installed(&mut self, installed: Installed) { + self.installed = Some(installed); + } + + /// Record where a download stands (the worker writes through its own handle; this is for a + /// caller that has the file already, and for tests). + pub fn set_progress(&mut self, progress: Progress) { + self.progress = progress; + } +} + +impl Drop for Updater { + /// Quitting while a download runs stops it instead of leaving a half file behind. + fn drop(&mut self) { + if let Some(job) = &self.job { + job.cancel.store(true, Ordering::Relaxed); + } + } +} + +fn load_prefs(dir: &Path) -> Prefs { + let path = dir.join(SETTINGS_FILE); + let Ok(text) = std::fs::read(&path) else { return Prefs::default() }; + match serde_json::from_slice::(&text) { + Ok(f) if f.version <= SETTINGS_VERSION => f.updates, + Ok(f) => { + log::warn!("updates: {} was written by a newer version ({})", path.display(), f.version); + Prefs::default() + } + Err(e) => { + log::warn!("updates: {} could not be read ({e}); the defaults are used", path.display()); + Prefs::default() + } + } +} + +/// The platform as the dialog words it (`linux-x86_64`). +pub fn platform_text() -> String { + match lcc_updater::Target::current() { + Some(t) => format!("{}-{}", t.os.slug(), t.arch), + None => format!("{}-{}", std::env::consts::OS, std::env::consts::ARCH), + } +} + +/// Whether this build has updates at all (the platforms we do not package do not). +pub fn platform_supported() -> bool { + lcc_updater::Target::current().is_some() +} + +/// `YYYY-MM-DDTHH:MM:SSZ` now, by hand (the engine carries no date crate). +pub fn iso_now() -> String { + let secs = web_time::SystemTime::now().duration_since(web_time::UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0); + iso_from_unix(secs) +} + +/// [`iso_now`] for a Unix timestamp. +pub fn iso_from_unix(secs: u64) -> String { + let days = secs / 86_400; + let (h, m, s) = ((secs % 86_400) / 3_600, (secs % 3_600) / 60, secs % 60); + let (y, mo, d) = civil_from_days(days as i64); + format!("{y:04}-{mo:02}-{d:02}T{h:02}:{m:02}:{s:02}Z") +} + +/// Days since 1970-01-01 to a calendar date (Howard Hinnant's `civil_from_days`). +fn civil_from_days(days: i64) -> (i64, u32, u32) { + let z = days + 719_468; + let era = z.div_euclid(146_097); + let doe = z.rem_euclid(146_097); + let yoe = (doe - doe / 1_460 + doe / 36_524 - doe / 146_096) / 365; + let y = yoe + era * 400; + let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); + let mp = (5 * doy + 2) / 153; + let d = (doy - (153 * mp + 2) / 5 + 1) as u32; + let m = if mp < 10 { mp + 3 } else { mp - 9 } as u32; + (if m <= 2 { y + 1 } else { y }, m, d) +} + +fn available_json(a: &Available) -> Value { + json!({ + "version": a.version, + "current": a.current, + "title": a.title, + "tag": a.tag, + "published": a.published, + "notes": a.notes, + "file": a.file, + "size": a.size, + "action": a.action, + "verified": a.sha256.is_some(), + "kind": a.kind.text(), + }) +} + +fn staged_json(s: &Staged) -> Value { + json!({ + "version": s.version, + "file": s.file, + "bytes": s.bytes, + "sha256": s.sha256, + "path": s.path.to_string_lossy(), + "kind": s.kind.text(), + }) +} + +/// The install plan of a staged file, as the dialog words it. +pub fn plan(s: &Staged) -> lcc_updater::Plan { + lcc_updater::plan(s.kind.to_crate(), &s.path, &s.version) +} + +/// Apply a staged update. The returned [`Installed`] says whether the app has to quit. +pub fn install(s: &Staged) -> Result { + let outcome = lcc_updater::install(s.kind.to_crate(), &downloaded(s), &s.version).map_err(|e| e.to_string())?; + Ok(Installed { version: s.version.clone(), message: outcome.message, exit: outcome.exit }) +} + +fn downloaded(s: &Staged) -> lcc_updater::Downloaded { + lcc_updater::Downloaded { path: s.path.clone(), bytes: s.bytes, sha256: s.sha256.clone(), name: s.file.clone() } +} + +/// Delete a staged file the user does not want to install. +pub fn discard(s: &Staged) { + if let Err(e) = std::fs::remove_file(&s.path) + && e.kind() != std::io::ErrorKind::NotFound + { + log::warn!("updates: {}: {e}", s.path.display()); + } +} + +#[cfg(test)] +mod tests; diff --git a/crates/engine/src/update/tests.rs b/crates/engine/src/update/tests.rs new file mode 100644 index 0000000000..e2f53100ab --- /dev/null +++ b/crates/engine/src/update/tests.rs @@ -0,0 +1,432 @@ +//! The updater's session state: settings, the check's outcome, a download's progress, and the +//! status a frontend reads. The network itself is the crate's own business (`lcc-updater`), so +//! these tests feed the state directly. + +use super::*; + +fn scratch(tag: &str) -> PathBuf { + let d = std::env::temp_dir().join(format!("lcc-engine-update-{tag}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&d); + std::fs::create_dir_all(&d).expect("scratch"); + d +} + +fn update(version: &str) -> lcc_updater::Update { + lcc_updater::Update { + current: lcc_updater::Version::parse("1.0.0").expect("v"), + version: lcc_updater::Version::parse(version).expect("v"), + title: format!("App {version}"), + tag: format!("v{version}"), + asset: lcc_updater::Asset { + name: format!("app-{version}-windows-x64.msi"), + url: "https://example.invalid/a.msi".into(), + size: 1_000, + sha256: None, + kind: lcc_updater::Kind::Msi, + }, + sha256: Some("ab".repeat(32)), + published: Some("2026-10-12".into()), + notes: "### Fixed\n- things".into(), + action: "run the 64-bit installer and then start the app again".into(), + } +} + +#[test] +fn a_check_that_finds_a_release_reports_it() { + let mut u = Updater::new(Some(scratch("found"))); + assert_eq!(u.check(), &Check::Never); + u.apply(lcc_updater::Checked::Found(Box::new(update("1.2.0")))); + let a = u.available().expect("available"); + assert_eq!((a.version.as_str(), a.current.as_str()), ("1.2.0", "1.0.0")); + assert_eq!(a.file, "app-1.2.0-windows-x64.msi"); + assert_eq!(a.kind, Kind::Msi); + assert!(a.sha256.is_some()); + let s = u.status(); + assert_eq!((s["check"].as_str(), s["download"].as_str()), (Some("found"), Some("idle"))); + assert_eq!(s["available"]["version"], "1.2.0"); + assert_eq!(s["available"]["kind"], "msi"); + assert_eq!(s["supported"], json!(platform_supported())); + assert!(s["lastChecked"].as_str().is_some(), "{s}"); + let _ = std::fs::remove_dir_all(u.stage_dir()); +} + +#[test] +fn a_current_build_and_a_failure_are_both_reported() { + let dir = scratch("current"); + let mut u = Updater::new(Some(dir.clone())); + u.apply(lcc_updater::Checked::Current("1.0.0".into())); + assert_eq!(u.check(), &Check::Current); + assert!(u.available().is_none()); + u.apply(lcc_updater::Checked::Failed("no network".into())); + assert_eq!(u.check(), &Check::Never, "a failure is not an answer"); + assert_eq!(u.status()["error"], "no network"); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn settings_are_written_and_read_back() { + let dir = scratch("prefs"); + { + let mut u = Updater::new(Some(dir.clone())); + assert!(u.prefs().check_at_startup, "on by default"); + assert!(!u.prefs().prerelease); + assert!(u.set_prefs(Some(false), Some(true)), "a change is saved"); + assert!(!u.set_prefs(Some(false), Some(true)), "the same values change nothing"); + u.mark_seen("1.2.0", true); + } + let again = Updater::new(Some(dir.clone())); + assert!(!again.prefs().check_at_startup); + assert!(again.prefs().prerelease); + assert!(again.already_seen("1.2.0")); + assert!(!again.already_seen("1.3.0")); + let file: serde_json::Value = serde_json::from_slice(&std::fs::read(dir.join("updates.json")).expect("read")).expect("json"); + assert_eq!(file["version"], 1); + assert_eq!(file["updates"]["seenVersion"]["skipped"], true); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn a_settings_file_from_a_newer_build_is_left_alone() { + let dir = scratch("newer"); + std::fs::write(dir.join("updates.json"), br#"{"version": 99, "updates": {"checkAtStartup": false}}"#).expect("write"); + let u = Updater::new(Some(dir.clone())); + assert!(u.prefs().check_at_startup, "the defaults are used rather than guessed at"); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn a_damaged_settings_file_is_survivable() { + let dir = scratch("damaged"); + std::fs::write(dir.join("updates.json"), b"{not json").expect("write"); + let u = Updater::new(Some(dir.clone())); + assert_eq!(u.prefs(), &Prefs::default()); + // and the file is not removed by reading it + assert!(dir.join("updates.json").exists()); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn an_in_memory_session_writes_nothing() { + let mut u = Updater::new(None); + assert!(!u.persistent()); + assert!(u.set_prefs(Some(false), None)); + u.mark_seen("9.9.9", false); + // staged in a temporary folder, which is where a download would land + assert!(u.stage_dir().to_string_lossy().contains("updates")); +} + +#[test] +fn a_staged_file_is_reported_and_can_be_discarded() { + let dir = scratch("staged"); + let file = dir.join("app-1.2.0-windows-x64.msi"); + std::fs::write(&file, b"installer").expect("write"); + let mut u = Updater::new(Some(dir.clone())); + u.apply(lcc_updater::Checked::Found(Box::new(update("1.2.0")))); + let staged = Staged { + version: "1.2.0".into(), + path: file.clone(), + bytes: 9, + sha256: "cd".repeat(32), + file: "app-1.2.0-windows-x64.msi".into(), + kind: Kind::Msi, + notes: String::new(), + }; + u.progress = Progress::Ready(Box::new(staged.clone())); + let s = u.status(); + assert_eq!(s["download"], "ready"); + assert_eq!(s["staged"]["version"], "1.2.0"); + assert_eq!(s["staged"]["kind"], "msi"); + discard(&staged); + assert!(!file.exists()); + discard(&staged); // a second time is not an error + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn a_newer_release_replaces_a_staged_older_one() { + let dir = scratch("replace"); + let mut u = Updater::new(Some(dir.clone())); + u.progress = Progress::Ready(Box::new(Staged { + version: "1.1.0".into(), + path: dir.join("old.msi"), + bytes: 1, + sha256: String::new(), + file: "old.msi".into(), + kind: Kind::Msi, + notes: String::new(), + })); + u.apply(lcc_updater::Checked::Found(Box::new(update("1.2.0")))); + assert_eq!(u.progress(), &Progress::Idle, "the newer release is what would be installed"); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn installing_without_an_update_is_refused_not_panicked() { + let mut u = Updater::new(None); + let activity = Activity::default(); + let err = u.start_download(&activity).expect_err("nothing to download"); + assert!(err.contains("check again"), "{err}"); +} + +#[test] +fn an_install_outcome_is_shown_once() { + let mut u = Updater::new(None); + assert!(u.installed().is_none()); + u.set_installed(Installed { version: "1.2.0".into(), message: "the installer is running".into(), exit: true }); + let s = u.status(); + assert_eq!(s["installed"]["version"], "1.2.0"); + assert_eq!(s["installed"]["exit"], true); + u.clear_installed(); + assert!(u.status().get("installed").is_none()); +} + +#[test] +fn the_platform_and_the_clock_are_worded_for_a_dialog() { + let text = platform_text(); + assert!(text.contains('-'), "{text}"); + assert_eq!(platform_supported(), lcc_updater::Target::current().is_some()); + // 2026-10-12T09:31:00Z + assert_eq!(iso_from_unix(1_760_261_460), "2025-10-12T09:31:00Z"); + assert_eq!(iso_from_unix(0), "1970-01-01T00:00:00Z"); + assert_eq!(iso_from_unix(86_399), "1970-01-01T23:59:59Z"); + assert_eq!(iso_from_unix(951_782_400), "2000-02-29T00:00:00Z", "a leap day"); + let now = iso_now(); + assert_eq!(now.len(), 20, "{now}"); + assert!(now.ends_with('Z')); +} + +#[test] +fn a_check_started_with_no_network_ends_as_a_message() { + // 127.0.0.1:1 is closed: the check must come back as an error, not a panic or a hang + let dir = scratch("offline"); + let mut u = Updater::new(Some(dir.clone())); + let opts = lcc_updater::Options { manifest_url: Some("http://127.0.0.1:1/latest.json".into()), ..u.options() }; + let checked = match lcc_updater::check(&opts, None, None) { + Ok(_) => lcc_updater::Checked::Current("1.0.0".into()), + Err(e) => lcc_updater::Checked::Failed(e.to_string()), + }; + assert!(matches!(checked, lcc_updater::Checked::Failed(_)), "nothing listens there"); + u.apply(checked); + assert_eq!(u.check(), &Check::Never); + assert!(u.status()["error"].as_str().is_some_and(|e| !e.is_empty())); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn the_options_follow_the_prerelease_setting() { + let mut u = Updater::new(None); + assert!(!u.options().prerelease); + u.set_prefs(None, Some(true)); + assert!(u.options().prerelease); + assert_eq!(u.options().repo, lcc_brand::REPOSITORY); +} + +/// A local server that answers every request with a small install payload: the whole update +/// pipeline, with no internet. +fn serve_installer(body: Vec, slow: bool) -> String { + use std::io::{BufRead, BufReader, Write}; + let l = std::net::TcpListener::bind("127.0.0.1:0").expect("bind"); + let base = format!("http://{}/release", l.local_addr().expect("addr")); + std::thread::spawn(move || { + for mut s in l.incoming().flatten() { + let mut r = BufReader::new(s.try_clone().expect("clone")); + loop { + let mut line = String::new(); + if r.read_line(&mut line).unwrap_or(0) == 0 || line.trim().is_empty() { + break; + } + } + let _ = s.write_all(format!("HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", body.len()).as_bytes()); + for chunk in body.chunks(8192) { + if s.write_all(chunk).is_err() { + return; + } + if slow { + std::thread::sleep(std::time::Duration::from_millis(40)); + } + } + } + }); + base +} + +/// Offer `url` as the update for `version`, as a check would. +fn offer(u: &mut Updater, version: &str, url: &str, bytes: usize) { + let file = format!("app-{version}-windows-x64.msi"); + u.apply(lcc_updater::Checked::Found(Box::new(lcc_updater::Update { + current: lcc_updater::Version::parse("1.0.0").expect("v"), + version: lcc_updater::Version::parse(version).expect("v"), + title: format!("App {version}"), + tag: format!("v{version}"), + asset: lcc_updater::Asset { name: file, url: url.to_string(), size: bytes as u64, sha256: None, kind: lcc_updater::Kind::Msi }, + sha256: None, + published: Some("2026-10-12".into()), + notes: "### Fixed".into(), + action: "run the installer".into(), + }))); +} + +#[test] +fn a_download_runs_in_the_activity_stack_and_stages_the_file() { + let dir = scratch("download"); + let body: Vec = (0..300_000u32).map(|i| (i % 251) as u8).collect(); + let url = serve_installer(body.clone(), false); + let activity = Activity::default(); + let mut u = Updater::new(Some(dir.clone())); + offer(&mut u, "1.2.0", &format!("{url}/app.msi"), body.len()); + u.start_download(&activity).expect("start"); + assert!(u.downloading(), "the transfer is in flight"); + let rows = activity.list(); + assert_eq!(rows.len(), 1, "the download holds an activity row"); + assert_eq!((rows[0].kind, rows[0].label.as_str()), (ACTIVITY_KIND, ACTIVITY_LABEL)); + assert!(rows[0].cancellable); + assert_eq!(rows[0].unit, Unit::Bytes); + u.wait_for_download(); + let staged = u.staged().expect("staged").clone(); + assert_eq!(staged.version, "1.2.0"); + assert_eq!(staged.bytes, body.len() as u64); + assert_eq!(std::fs::read(&staged.path).expect("read"), body); + assert_eq!(staged.sha256.len(), 64, "the file's own hash is recorded"); + assert!(activity.list().is_empty(), "the row goes with the transfer"); + let s = u.status(); + assert_eq!(s["download"], "ready"); + assert_eq!(s["staged"]["bytes"], body.len()); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn a_cancelled_download_leaves_the_old_installation_alone() { + let dir = scratch("cancel"); + let body: Vec = (0..400_000u32).map(|i| (i % 97) as u8).collect(); + let url = serve_installer(body.clone(), true); + let activity = Activity::default(); + let mut u = Updater::new(Some(dir.clone())); + offer(&mut u, "1.2.0", &format!("{url}/app.msi"), body.len()); + u.start_download(&activity).expect("start"); + assert!(u.cancel_download(), "there was a transfer to stop"); + u.wait_for_download(); + assert_eq!(u.progress(), &Progress::Cancelled); + assert!(activity.list().is_empty()); + assert!(u.staged().is_none(), "nothing is offered for install"); + // the partial file is not kept under its real name + assert!(!dir.join("updates").join("app-1.2.0-windows-x64.msi").exists()); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn a_download_that_cannot_reach_the_server_is_a_message() { + let dir = scratch("down"); + let activity = Activity::default(); + let mut u = Updater::new(Some(dir.clone())); + offer(&mut u, "1.2.0", "http://127.0.0.1:1/app.msi", 1_000); + u.start_download(&activity).expect("start"); + u.wait_for_download(); + let Progress::Failed(why) = u.progress() else { panic!("{:?}", u.progress()) }; + assert!(!why.is_empty(), "{why}"); + assert!(u.status()["error"].as_str().is_some_and(|e| !e.is_empty())); + assert!(activity.list().is_empty(), "the row does not stay behind"); + let _ = std::fs::remove_dir_all(&dir); +} + +/// A tiny release server: `GET /latest.json` (the manifest this run builds), `GET /sums` (the +/// release's `SHA256SUMS.txt`) and `GET /app.msi` (the installer). Returns its base URL. +fn serve_feed(installer: Vec, sha: String, file: String) -> String { + use std::io::{BufRead, BufReader, Write}; + let l = std::net::TcpListener::bind("127.0.0.1:0").expect("bind"); + let addr = l.local_addr().expect("addr"); + let base = format!("http://{addr}"); + let manifest = serde_json::json!({ + "version": "9.9.9", + "name": "App 9.9.9", + "notes": "### Fixed\n- the whole path", + "pub_date": "2026-10-12T00:00:00Z", + "releases": [{ + "tag": "v9.9.9", + "name": "App 9.9.9", + "notes": "### Fixed\n- the whole path", + "date": "2026-10-12", + "prerelease": false, + "assets": [ + {"name": file, "url": format!("{base}/app.msi"), "size": installer.len()}, + {"name": "SHA256SUMS.txt", "url": format!("{base}/sums"), "size": 90}, + ], + }], + }) + .to_string(); + let sums = format!("{sha} {file}\n"); + std::thread::spawn(move || { + for stream in l.incoming().flatten() { + let mut s = stream; + let mut r = BufReader::new(s.try_clone().expect("clone")); + let mut request = String::new(); + let _ = r.read_line(&mut request); + loop { + let mut line = String::new(); + if r.read_line(&mut line).unwrap_or(0) == 0 || line.trim().is_empty() { + break; + } + } + let path = request.split_whitespace().nth(1).unwrap_or("").to_string(); + let body: &[u8] = match path.as_str() { + "/latest.json" => manifest.as_bytes(), + "/sums" => sums.as_bytes(), + "/app.msi" => &installer, + _ => { + let _ = s.write_all(b"HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"); + continue; + } + }; + let _ = s.write_all(format!("HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", body.len()).as_bytes()); + let _ = s.write_all(body); + } + }); + base +} + +/// The whole path a release takes: a feed is read, the newer version is picked, its file is fetched +/// over HTTP, checked against the release's SHA-256 and staged, and the plan is what this platform +/// would do with it. +#[test] +fn the_whole_path_from_a_feed_to_a_staged_file() { + let dir = scratch("e2e"); + let installer: Vec = (0..120_000u32).map(|i| (i % 233) as u8).collect(); + let installer_sha = { + use sha2::Digest as _; + let mut h = sha2::Sha256::new(); + h.update(&installer); + h.finalize().iter().map(|b| format!("{b:02x}")).collect::() + }; + let target = lcc_updater::Target::current().expect("a platform to update"); + let file = format!("app-9.9.9-{}-{}.msi", target.os.slug(), target.arch); + let base = serve_feed(installer.clone(), installer_sha.clone(), file.clone()); + + let activity = Activity::default(); + let mut u = Updater::new(Some(dir.clone())); + u.set_manifest_url(Some(format!("{base}/latest.json"))); + assert_eq!(u.manifest_url(), Some(format!("{base}/latest.json").as_str())); + // 1. the check reads the feed and picks the file for this platform, with the release's hash + u.check_now(); + let available = u.available().cloned().expect("an update"); + assert_eq!(available.version, "9.9.9"); + assert_eq!(available.file, file); + assert_eq!(available.size, installer.len() as u64); + assert_eq!(available.sha256.as_deref(), Some(installer_sha.as_str()), "the checksum list is read too"); + assert!(available.notes.contains("the whole path")); + assert_eq!(available.action, target.describe(), "the plan is worded for this machine"); + // 2. the download fetches, checks and stages it + u.start_download(&activity).expect("start"); + u.wait_for_download(); + let staged = u.staged().cloned().expect("a staged file"); + assert_eq!(std::fs::read(&staged.path).expect("read"), installer); + assert_eq!(staged.sha256, installer_sha); + assert_eq!(staged.version, "9.9.9"); + assert!(activity.list().is_empty(), "the row goes with the transfer"); + // 3. what installing would do here + let plan = plan(&staged); + assert!(!plan.summary.is_empty()); + assert!(!plan.steps.is_empty()); + // 4. a second check finds the same release and keeps the staged file + u.check_now(); + assert!(u.staged().is_some(), "the same release does not throw its own download away"); + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/crates/net/src/download.rs b/crates/net/src/download.rs index c7d3a3f8c1..1913b5447d 100644 --- a/crates/net/src/download.rs +++ b/crates/net/src/download.rs @@ -90,7 +90,10 @@ impl Client { if let Some(c) = &opts.cancel { req = req.cancel(c.clone()); } - let done_already = opts.size.is_some_and(|s| s == have && s > 0); + // A partial file that is already the whole size is only usable when nothing has to be + // verified against it: with an expected SHA-256 the transfer runs again (a resumed file's + // hash would never be checked otherwise, so a damaged one could be renamed into place). + let done_already = opts.size.is_some_and(|s| s == have && s > 0) && opts.sha256.is_none(); if have > 0 && !done_already { req = req.header("Range", &format!("bytes={have}-")); } diff --git a/crates/ui-egui/Cargo.toml b/crates/ui-egui/Cargo.toml index 389ec8bff1..9bf48f7824 100644 --- a/crates/ui-egui/Cargo.toml +++ b/crates/ui-egui/Cargo.toml @@ -50,6 +50,8 @@ lcc-denoise = { workspace = true, features = ["runtime"] } lcc-codecs = { workspace = true } lcc-faces = { workspace = true } lcc-merge = { workspace = true } +# the update tests offer a release the way a check would (native only, like the updater itself) +lcc-updater = { workspace = true } filmcraft-h264enc = { git = "https://github.com/storytold/filmcraft", rev = "156086dc87282026aeec33f8a220e4629bccbe31" } filmcraft-isobmff = { git = "https://github.com/storytold/filmcraft", rev = "156086dc87282026aeec33f8a220e4629bccbe31" } wat = "1.228" # G19: a slow export-hook plug-in for the worker test diff --git a/crates/ui-egui/locales/fork/de-formats.json b/crates/ui-egui/locales/fork/de-formats.json index ba634db9c7..fa4b8f3b17 100644 --- a/crates/ui-egui/locales/fork/de-formats.json +++ b/crates/ui-egui/locales/fork/de-formats.json @@ -53,5 +53,15 @@ "Trained on: {provenance}": "Trainiert mit: {provenance}", "{} · {}. Kept in the library's “denoise” folder; the oldest ones that no photo uses go first when the limit is reached.": "{} · {}. Gespeichert im Ordner „denoise“ der Bibliothek; ist die Obergrenze erreicht, werden zuerst die ältesten Bilder entfernt, die kein Foto mehr verwendet.", "{} of {} from {host}": "{} von {} von {host}", + "{app} {version}": "{app} {version}", + "{app} {version} is available (Help ▸ Check for Updates…)": "{app} {version} ist verfügbar (Hilfe ▸ Nach Updates suchen…)", + "Version {version} is available.": "Version {version} ist verfügbar.", + "{file} · {published}": "{file} · {published}", + "{info} · {size}": "{info} · {size}", + "Installing it will {action}.": "Die Installation wird: {action}.", + "Last checked {when}": "Zuletzt geprüft: {when}", + "{done} of {total} ({percent} %)": "{done} von {total} ({percent} %)", + "{done} downloaded": "{done} heruntergeladen", + "{file} is downloaded and checked; install it to update (the app restarts).": "{file} ist heruntergeladen und geprüft; installieren Sie es, um zu aktualisieren (die App startet neu).", "Color space: Rec. 2020 {curve} (HDR AVIF)": "Farbraum: Rec. 2020 {curve} (HDR-AVIF)" } diff --git a/crates/ui-egui/locales/fork/de.json b/crates/ui-egui/locales/fork/de.json index ff903dd988..e2d5a0cf42 100644 --- a/crates/ui-egui/locales/fork/de.json +++ b/crates/ui-egui/locales/fork/de.json @@ -1117,6 +1117,25 @@ "is in this week": "liegt in dieser Woche", "is in this month": "liegt in diesem Monat", "is in this year": "liegt in diesem Jahr", + "Check for Updates…": "Nach Updates suchen…", + "Install Update and Relaunch": "Update installieren und neu starten", + "Checking for updates…": "Suche nach Updates…", + "This is the newest version.": "Dies ist die neueste Version.", + "The download is checked against the release's SHA-256 before anything is installed.": "Der Download wird gegen die SHA-256 des Releases geprüft, bevor etwas installiert wird.", + "The download is checked against the size the release states.": "Der Download wird gegen die vom Release angegebene Größe geprüft.", + "This build has no updates of its own: the releases page has the files for the platforms we ship.": "Dieser Build hat keine eigenen Updates: Die Release-Seite enthält die Dateien für die von uns gebauten Plattformen.", + "Open the releases page": "Öffne die Release-Seite", + "Cancel Download": "Download abbrechen", + "The download could not be finished.": "Der Download konnte nicht abgeschlossen werden.", + "The download was cancelled.": "Der Download wurde abgebrochen.", + "Quit the app to let the installer finish.": "Beenden Sie die App, damit das Installationsprogramm fertig werden kann.", + "Check Again": "Erneut suchen", + "Download": "Herunterladen", + "Install and Relaunch": "Installieren und neu starten", + "Skip This Version": "Diese Version überspringen", + "Check for updates when the app starts": "Beim Start nach Updates suchen", + "Include prereleases (release candidates)": "Vorabversionen (Release Candidates) einschließen", + "These settings are saved in the app's settings folder.": "Diese Einstellungen werden im Einstellungsordner der App gespeichert.", "File date": "Dateidatum", "HDR curve": "HDR-Kurve" } diff --git a/crates/ui-egui/locales/fork/es-formats.json b/crates/ui-egui/locales/fork/es-formats.json index cf6f709359..11a9765985 100644 --- a/crates/ui-egui/locales/fork/es-formats.json +++ b/crates/ui-egui/locales/fork/es-formats.json @@ -53,5 +53,15 @@ "Trained on: {provenance}": "Entrenado con: {provenance}", "{} · {}. Kept in the library's “denoise” folder; the oldest ones that no photo uses go first when the limit is reached.": "{} · {}. Se guardan en la carpeta «denoise» de la biblioteca; al alcanzar el límite, se eliminan primero las más antiguas que ninguna foto usa.", "{} of {} from {host}": "{} de {} desde {host}", + "{app} {version}": "{app} {version}", + "{app} {version} is available (Help ▸ Check for Updates…)": "{app} {version} está disponible (Ayuda ▸ Buscar actualizaciones…)", + "Version {version} is available.": "La versión {version} está disponible.", + "{file} · {published}": "{file} · {published}", + "{info} · {size}": "{info} · {size}", + "Installing it will {action}.": "Al instalarla se hará lo siguiente: {action}.", + "Last checked {when}": "Última comprobación: {when}", + "{done} of {total} ({percent} %)": "{done} de {total} ({percent} %)", + "{done} downloaded": "{done} descargados", + "{file} is downloaded and checked; install it to update (the app restarts).": "{file} se ha descargado y comprobado; instálalo para actualizar (la aplicación se reinicia).", "Color space: Rec. 2020 {curve} (HDR AVIF)": "Espacio de color: Rec. 2020 {curve} (AVIF HDR)" } diff --git a/crates/ui-egui/locales/fork/es.json b/crates/ui-egui/locales/fork/es.json index b89420ac43..fda95cc14b 100644 --- a/crates/ui-egui/locales/fork/es.json +++ b/crates/ui-egui/locales/fork/es.json @@ -1260,6 +1260,25 @@ "is in this week": "está en esta semana", "is in this month": "está en este mes", "is in this year": "está en este año", + "Check for Updates…": "Buscar actualizaciones…", + "Install Update and Relaunch": "Instalar la actualización y reiniciar", + "Checking for updates…": "Buscando actualizaciones…", + "This is the newest version.": "Esta es la versión más reciente.", + "The download is checked against the release's SHA-256 before anything is installed.": "La descarga se comprueba con el SHA-256 de la versión antes de instalar nada.", + "The download is checked against the size the release states.": "La descarga se comprueba con el tamaño indicado por la versión.", + "This build has no updates of its own: the releases page has the files for the platforms we ship.": "Esta compilación no tiene actualizaciones propias: la página de versiones tiene los archivos de las plataformas que publicamos.", + "Open the releases page": "Abrir la página de versiones", + "Cancel Download": "Cancelar la descarga", + "The download could not be finished.": "No se pudo completar la descarga.", + "The download was cancelled.": "Se canceló la descarga.", + "Quit the app to let the installer finish.": "Sal de la aplicación para que el instalador termine.", + "Check Again": "Buscar de nuevo", + "Download": "Descargar", + "Install and Relaunch": "Instalar y reiniciar", + "Skip This Version": "Omitir esta versión", + "Check for updates when the app starts": "Buscar actualizaciones al iniciar la aplicación", + "Include prereleases (release candidates)": "Incluir versiones preliminares (candidatas)", + "These settings are saved in the app's settings folder.": "Estos ajustes se guardan en la carpeta de ajustes de la aplicación.", "File date": "Fecha del archivo", "HDR curve": "Curva HDR" } diff --git a/crates/ui-egui/locales/fork/fr-formats.json b/crates/ui-egui/locales/fork/fr-formats.json index 98cdb2f361..586d0a3576 100644 --- a/crates/ui-egui/locales/fork/fr-formats.json +++ b/crates/ui-egui/locales/fork/fr-formats.json @@ -43,5 +43,15 @@ "Location {n}": "Lieu {n}", "{n} photos · {frames} frames · {secs} s": "{n} photos · {frames} images · {secs} s", "Exported timelapse: {photos} photos, {frames} frames": "Timelapse exporté : {photos} photos, {frames} images", + "{app} {version}": "{app} {version}", + "{app} {version} is available (Help ▸ Check for Updates…)": "{app} {version} est disponible (Aide ▸ Rechercher des mises à jour…)", + "Version {version} is available.": "La version {version} est disponible.", + "{file} · {published}": "{file} · {published}", + "{info} · {size}": "{info} · {size}", + "Installing it will {action}.": "L’installation va : {action}.", + "Last checked {when}": "Dernière vérification : {when}", + "{done} of {total} ({percent} %)": "{done} sur {total} ({percent} %)", + "{done} downloaded": "{done} téléchargés", + "{file} is downloaded and checked; install it to update (the app restarts).": "{file} est téléchargé et vérifié ; installez-le pour mettre à jour (l’application redémarre).", "Color space: Rec. 2020 {curve} (HDR AVIF)": "Espace colorimétrique : Rec. 2020 {curve} (AVIF HDR)" } diff --git a/crates/ui-egui/locales/fork/fr.json b/crates/ui-egui/locales/fork/fr.json index 1276b528b6..12d06926c5 100644 --- a/crates/ui-egui/locales/fork/fr.json +++ b/crates/ui-egui/locales/fork/fr.json @@ -1166,6 +1166,25 @@ "is in this week": "est dans cette semaine", "is in this month": "est dans ce mois", "is in this year": "est dans cette année", + "Check for Updates…": "Rechercher des mises à jour…", + "Install Update and Relaunch": "Installer la mise à jour et redémarrer", + "Checking for updates…": "Recherche des mises à jour…", + "This is the newest version.": "C’est la version la plus récente.", + "The download is checked against the release's SHA-256 before anything is installed.": "Le téléchargement est vérifié par le SHA-256 de la version avant toute installation.", + "The download is checked against the size the release states.": "Le téléchargement est vérifié par rapport à la taille annoncée.", + "This build has no updates of its own: the releases page has the files for the platforms we ship.": "Cette compilation n’a pas de mises à jour propres : la page des versions contient les fichiers des plateformes que nous publions.", + "Open the releases page": "Ouvrir la page des versions", + "Cancel Download": "Annuler le téléchargement", + "The download could not be finished.": "Le téléchargement n’a pas pu aboutir.", + "The download was cancelled.": "Le téléchargement a été annulé.", + "Quit the app to let the installer finish.": "Quittez l’application pour laisser l’installateur terminer.", + "Check Again": "Vérifier à nouveau", + "Download": "Télécharger", + "Install and Relaunch": "Installer et redémarrer", + "Skip This Version": "Ignorer cette version", + "Check for updates when the app starts": "Rechercher des mises à jour au démarrage", + "Include prereleases (release candidates)": "Inclure les préversions (release candidates)", + "These settings are saved in the app's settings folder.": "Ces réglages sont enregistrés dans le dossier de réglages de l’application.", "File date": "Date du fichier", "HDR curve": "Courbe HDR" } diff --git a/crates/ui-egui/locales/fork/ja-formats.json b/crates/ui-egui/locales/fork/ja-formats.json index 1563860fec..7e3b605801 100644 --- a/crates/ui-egui/locales/fork/ja-formats.json +++ b/crates/ui-egui/locales/fork/ja-formats.json @@ -53,5 +53,15 @@ "Trained on: {provenance}": "学習データ:{provenance}", "{} · {}. Kept in the library's “denoise” folder; the oldest ones that no photo uses go first when the limit is reached.": "{} · {}。ライブラリの「denoise」フォルダーに保存されます。上限に達すると、どの写真にも使われていない古いものから削除されます。", "{} of {} from {host}": "{host}から {}/{}", + "{app} {version}": "{app} {version}", + "{app} {version} is available (Help ▸ Check for Updates…)": "{app} {version} が利用できます(ヘルプ ▸ 更新を確認…)", + "Version {version} is available.": "バージョン {version} が利用できます。", + "{file} · {published}": "{file} ・{published}", + "{info} · {size}": "{info} ・{size}", + "Installing it will {action}.": "インストールすると{action}。", + "Last checked {when}": "最後の確認: {when}", + "{done} of {total} ({percent} %)": "{done} / {total}({percent} %)", + "{done} downloaded": "{done} ダウンロード済み", + "{file} is downloaded and checked; install it to update (the app restarts).": "{file} をダウンロードして検証しました。インストールすると更新されます(アプリは再起動します)。", "Color space: Rec. 2020 {curve} (HDR AVIF)": "カラースペース:Rec. 2020 {curve}(HDR AVIF)" } diff --git a/crates/ui-egui/locales/fork/ja.json b/crates/ui-egui/locales/fork/ja.json index d58396e6af..d32f4b8365 100644 --- a/crates/ui-egui/locales/fork/ja.json +++ b/crates/ui-egui/locales/fork/ja.json @@ -1257,6 +1257,25 @@ "is in this week": "が今週", "is in this month": "が今月", "is in this year": "が今年", + "Check for Updates…": "更新を確認…", + "Install Update and Relaunch": "更新をインストールして再起動", + "Checking for updates…": "更新を確認しています…", + "This is the newest version.": "これが最新バージョンです。", + "The download is checked against the release's SHA-256 before anything is installed.": "ダウンロードはインストール前にリリースの SHA-256 と照合します。", + "The download is checked against the size the release states.": "ダウンロードはリリースのサイズと照合します。", + "This build has no updates of its own: the releases page has the files for the platforms we ship.": "このビルドには独自の更新がありません。対応プラットフォームのファイルはリリースページにあります。", + "Open the releases page": "リリースページを開く", + "Cancel Download": "ダウンロードを中断", + "The download could not be finished.": "ダウンロードを完了できませんでした。", + "The download was cancelled.": "ダウンロードを中断しました。", + "Quit the app to let the installer finish.": "アプリを終了するとインストーラーが完了します。", + "Check Again": "再確認", + "Download": "ダウンロード", + "Install and Relaunch": "インストールして再起動", + "Skip This Version": "このバージョンをスキップ", + "Check for updates when the app starts": "起動時に更新を確認する", + "Include prereleases (release candidates)": "プリリリース(RC)も含める", + "These settings are saved in the app's settings folder.": "これらの設定はアプリの設定フォルダーに保存されます。", "File date": "ファイルの日付", "HDR curve": "HDR カーブ" } diff --git a/crates/ui-egui/locales/fork/pt-br-formats.json b/crates/ui-egui/locales/fork/pt-br-formats.json index 53e88334e2..7796c96e58 100644 --- a/crates/ui-egui/locales/fork/pt-br-formats.json +++ b/crates/ui-egui/locales/fork/pt-br-formats.json @@ -53,5 +53,15 @@ "Trained on: {provenance}": "Treinado com: {provenance}", "{} · {}. Kept in the library's “denoise” folder; the oldest ones that no photo uses go first when the limit is reached.": "{} · {}. Guardadas na pasta “denoise” da biblioteca; ao atingir o limite, as mais antigas que nenhuma foto usa saem primeiro.", "{} of {} from {host}": "{} de {} de {host}", + "{app} {version}": "{app} {version}", + "{app} {version} is available (Help ▸ Check for Updates…)": "{app} {version} está disponível (Ajuda ▸ Verificar atualizações…)", + "Version {version} is available.": "A versão {version} está disponível.", + "{file} · {published}": "{file} · {published}", + "{info} · {size}": "{info} · {size}", + "Installing it will {action}.": "A instalação vai {action}.", + "Last checked {when}": "Última verificação: {when}", + "{done} of {total} ({percent} %)": "{done} de {total} ({percent} %)", + "{done} downloaded": "{done} baixados", + "{file} is downloaded and checked; install it to update (the app restarts).": "{file} foi baixado e verificado; instale para atualizar (o aplicativo será reiniciado).", "Color space: Rec. 2020 {curve} (HDR AVIF)": "Espaço de cor: Rec. 2020 {curve} (AVIF HDR)" } diff --git a/crates/ui-egui/locales/fork/pt-br.json b/crates/ui-egui/locales/fork/pt-br.json index ee897090d9..f6683d09db 100644 --- a/crates/ui-egui/locales/fork/pt-br.json +++ b/crates/ui-egui/locales/fork/pt-br.json @@ -1257,6 +1257,25 @@ "is in this week": "está nesta semana", "is in this month": "está neste mês", "is in this year": "está neste ano", + "Check for Updates…": "Verificar atualizações…", + "Install Update and Relaunch": "Instalar a atualização e reiniciar", + "Checking for updates…": "Verificando atualizações…", + "This is the newest version.": "Esta é a versão mais recente.", + "The download is checked against the release's SHA-256 before anything is installed.": "O download é conferido com o SHA-256 da versão antes de qualquer instalação.", + "The download is checked against the size the release states.": "O download é conferido com o tamanho informado pela versão.", + "This build has no updates of its own: the releases page has the files for the platforms we ship.": "Esta compilação não tem atualizações próprias: a página de versões tem os arquivos das plataformas que publicamos.", + "Open the releases page": "Abrir a página de versões", + "Cancel Download": "Cancelar o download", + "The download could not be finished.": "Não foi possível concluir o download.", + "The download was cancelled.": "O download foi cancelado.", + "Quit the app to let the installer finish.": "Saia do aplicativo para o instalador terminar.", + "Check Again": "Verificar de novo", + "Download": "Baixar", + "Install and Relaunch": "Instalar e reiniciar", + "Skip This Version": "Ignorar esta versão", + "Check for updates when the app starts": "Verificar atualizações ao iniciar o aplicativo", + "Include prereleases (release candidates)": "Incluir pré-lançamentos (release candidates)", + "These settings are saved in the app's settings folder.": "Estes ajustes são salvos na pasta de configurações do aplicativo.", "File date": "Data do arquivo", "HDR curve": "Curva HDR" } diff --git a/crates/ui-egui/locales/fork/ru-formats.json b/crates/ui-egui/locales/fork/ru-formats.json index ef1e272c67..abfc8abf3e 100644 --- a/crates/ui-egui/locales/fork/ru-formats.json +++ b/crates/ui-egui/locales/fork/ru-formats.json @@ -57,5 +57,15 @@ "{} MB": "{} МБ", "{} of {} from {host}": "{} из {} с {host}", "{} · {}. Kept in the library's “denoise” folder; the oldest ones that no photo uses go first when the limit is reached.": "{} · {}. Хранятся в папке «denoise» библиотеки; при достижении ограничения первыми удаляются самые старые изображения, которые не использует ни одно фото.", + "{app} {version}": "{app} {version}", + "{app} {version} is available (Help ▸ Check for Updates…)": "Доступна версия {app} {version} («Справка» ▸ «Проверить обновления…»)", + "Version {version} is available.": "Доступна версия {version}.", + "{file} · {published}": "{file} · {published}", + "{info} · {size}": "{info} · {size}", + "Installing it will {action}.": "При установке: {action}.", + "Last checked {when}": "Последняя проверка: {when}", + "{done} of {total} ({percent} %)": "{done} из {total} ({percent} %)", + "{done} downloaded": "Загружено: {done}", + "{file} is downloaded and checked; install it to update (the app restarts).": "{file} загружен и проверен; установите его, чтобы обновиться (приложение перезапустится).", "Color space: Rec. 2020 {curve} (HDR AVIF)": "Цветовое пространство: Rec. 2020 {curve} (HDR AVIF)" } diff --git a/crates/ui-egui/locales/fork/ru.json b/crates/ui-egui/locales/fork/ru.json index e316d8ff2a..d817d1b2f9 100644 --- a/crates/ui-egui/locales/fork/ru.json +++ b/crates/ui-egui/locales/fork/ru.json @@ -1466,6 +1466,24 @@ "is in this week": "на этой неделе", "is in this month": "в этом месяце", "is in this year": "в этом году", + "Check for Updates…": "Проверить обновления…", + "Install Update and Relaunch": "Установить обновление и перезапустить", + "Checking for updates…": "Проверка обновлений…", + "This is the newest version.": "Это самая новая версия.", + "The download is checked against the release's SHA-256 before anything is installed.": "Перед установкой загрузка сверяется с SHA-256 релиза.", + "The download is checked against the size the release states.": "Загрузка сверяется с указанным размером релиза.", + "This build has no updates of its own: the releases page has the files for the platforms we ship.": "У этой сборки нет своих обновлений: файлы для наших платформ есть на странице релизов.", + "Open the releases page": "Открыть страницу релизов", + "Cancel Download": "Отменить загрузку", + "The download could not be finished.": "Не удалось завершить загрузку.", + "The download was cancelled.": "Загрузка отменена.", + "Quit the app to let the installer finish.": "Закройте приложение, чтобы установщик завершил работу.", + "Check Again": "Проверить снова", + "Install and Relaunch": "Установить и перезапустить", + "Skip This Version": "Пропустить эту версию", + "Check for updates when the app starts": "Проверять обновления при запуске", + "Include prereleases (release candidates)": "Включать предварительные версии (RC)", + "These settings are saved in the app's settings folder.": "Эти настройки сохраняются в папке настроек приложения.", "File date": "Дата файла", "HDR curve": "Кривая HDR" } diff --git a/crates/ui-egui/locales/fork/uk-formats.json b/crates/ui-egui/locales/fork/uk-formats.json index 49fc67b142..ec6bb7d279 100644 --- a/crates/ui-egui/locales/fork/uk-formats.json +++ b/crates/ui-egui/locales/fork/uk-formats.json @@ -43,5 +43,15 @@ "Location {n}": "Місце {n}", "{n} photos · {frames} frames · {secs} s": "Фото: {n} · кадрів: {frames} · {secs} с", "Exported timelapse: {photos} photos, {frames} frames": "Таймлапс експортовано: фото {photos}, кадрів {frames}", + "{app} {version}": "{app} {version}", + "{app} {version} is available (Help ▸ Check for Updates…)": "Доступна версія {app} {version} («Довідка» ▸ «Перевірити оновлення…»)", + "Version {version} is available.": "Доступна версія {version}.", + "{file} · {published}": "{file} · {published}", + "{info} · {size}": "{info} · {size}", + "Installing it will {action}.": "Під час встановлення: {action}.", + "Last checked {when}": "Остання перевірка: {when}", + "{done} of {total} ({percent} %)": "{done} з {total} ({percent} %)", + "{done} downloaded": "Завантажено: {done}", + "{file} is downloaded and checked; install it to update (the app restarts).": "{file} завантажено й перевірено; встановіть його, щоб оновитися (застосунок перезапуститься).", "Color space: Rec. 2020 {curve} (HDR AVIF)": "Колірний простір: Rec. 2020 {curve} (HDR AVIF)" } diff --git a/crates/ui-egui/locales/fork/uk.json b/crates/ui-egui/locales/fork/uk.json index d3072d93fe..a9897c5765 100644 --- a/crates/ui-egui/locales/fork/uk.json +++ b/crates/ui-egui/locales/fork/uk.json @@ -996,6 +996,25 @@ "is in this week": "цього тижня", "is in this month": "цього місяця", "is in this year": "цього року", + "Check for Updates…": "Перевірити оновлення…", + "Install Update and Relaunch": "Встановити оновлення й перезапустити", + "Checking for updates…": "Перевірка оновлень…", + "This is the newest version.": "Це найновіша версія.", + "The download is checked against the release's SHA-256 before anything is installed.": "Перед встановленням завантаження звіряється з SHA-256 релізу.", + "The download is checked against the size the release states.": "Завантаження звіряється з зазначеним розміром релізу.", + "This build has no updates of its own: the releases page has the files for the platforms we ship.": "У цієї збірки немає власних оновлень: файли для наших платформ є на сторінці релізів.", + "Open the releases page": "Відкрити сторінку релізів", + "Cancel Download": "Скасувати завантаження", + "The download could not be finished.": "Не вдалося завершити завантаження.", + "The download was cancelled.": "Завантаження скасовано.", + "Quit the app to let the installer finish.": "Закрийте застосунок, щоб инсталятор завершив роботу.", + "Check Again": "Перевірити знову", + "Download": "Завантажити", + "Install and Relaunch": "Встановити й перезапустити", + "Skip This Version": "Пропустити цю версію", + "Check for updates when the app starts": "Перевіряти оновлення під час запуску", + "Include prereleases (release candidates)": "Включати попередні версії (RC)", + "These settings are saved in the app's settings folder.": "Ці налаштування зберігаються в папці налаштувань застосунка.", "File date": "Дата файлу", "HDR curve": "Крива HDR" } diff --git a/crates/ui-egui/locales/fork/zh-hans-formats.json b/crates/ui-egui/locales/fork/zh-hans-formats.json index 141f11bee8..5a711e023f 100644 --- a/crates/ui-egui/locales/fork/zh-hans-formats.json +++ b/crates/ui-egui/locales/fork/zh-hans-formats.json @@ -53,5 +53,15 @@ "Trained on: {provenance}": "训练数据:{provenance}", "{} of {} from {host}": "{}/{},来自 {host}", "{} · {}. Kept in the library's “denoise” folder; the oldest ones that no photo uses go first when the limit is reached.": "{} · {}。保存在图库的“denoise”文件夹中;达到上限时,会先删除没有照片使用的最旧结果。", + "{app} {version}": "{app} {version}", + "{app} {version} is available (Help ▸ Check for Updates…)": "{app} {version} 已发布(帮助 ▸ 检查更新…)", + "Version {version} is available.": "版本 {version} 已发布。", + "{file} · {published}": "{file} · {published}", + "{info} · {size}": "{info} · {size}", + "Installing it will {action}.": "安装时将{action}。", + "Last checked {when}": "上次检查:{when}", + "{done} of {total} ({percent} %)": "{done} / {total}({percent} %)", + "{done} downloaded": "已下载 {done}", + "{file} is downloaded and checked; install it to update (the app restarts).": "已下载并校验 {file};安装即可更新(应用将重启)。", "Color space: Rec. 2020 {curve} (HDR AVIF)": "色彩空间:Rec. 2020 {curve}(HDR AVIF)" } diff --git a/crates/ui-egui/locales/fork/zh-hans.json b/crates/ui-egui/locales/fork/zh-hans.json index 19c6f70ad4..eab1ddbfb4 100644 --- a/crates/ui-egui/locales/fork/zh-hans.json +++ b/crates/ui-egui/locales/fork/zh-hans.json @@ -1170,6 +1170,25 @@ "is in this week": "在本周", "is in this month": "在本月", "is in this year": "在今年", + "Check for Updates…": "检查更新…", + "Install Update and Relaunch": "安装更新并重启", + "Checking for updates…": "正在检查更新…", + "This is the newest version.": "已是最新版本。", + "The download is checked against the release's SHA-256 before anything is installed.": "安装前会用发布的 SHA-256 校验下载内容。", + "The download is checked against the size the release states.": "下载会按发布标明的大小校验。", + "This build has no updates of its own: the releases page has the files for the platforms we ship.": "此构建没有自带更新:我们发布的平台文件在发布页上。", + "Open the releases page": "打开发布页", + "Cancel Download": "取消下载", + "The download could not be finished.": "无法完成下载。", + "The download was cancelled.": "已取消下载。", + "Quit the app to let the installer finish.": "退出应用后安装程序将完成。", + "Check Again": "再次检查", + "Download": "下载", + "Install and Relaunch": "安装并重启", + "Skip This Version": "跳过此版本", + "Check for updates when the app starts": "启动时检查更新", + "Include prereleases (release candidates)": "包含预发版(RC)", + "These settings are saved in the app's settings folder.": "这些设置保存在应用的设置文件夹中。", "File date": "文件日期", "HDR curve": "HDR 曲线" } diff --git a/crates/ui-egui/locales/fork/zh-hant-formats.json b/crates/ui-egui/locales/fork/zh-hant-formats.json index 78d76f046d..b8f6a09a36 100644 --- a/crates/ui-egui/locales/fork/zh-hant-formats.json +++ b/crates/ui-egui/locales/fork/zh-hant-formats.json @@ -53,5 +53,15 @@ "Trained on: {provenance}": "訓練資料:{provenance}", "{} of {} from {host}": "{}/{},來自 {host}", "{} · {}. Kept in the library's “denoise” folder; the oldest ones that no photo uses go first when the limit is reached.": "{} · {}。保存在照片庫的「denoise」檔案夾中;達到上限時,會先刪除沒有相片使用的最舊影像。", + "{app} {version}": "{app} {version}", + "{app} {version} is available (Help ▸ Check for Updates…)": "{app} {version} 已推出(說明 ▸ 檢查更新…)", + "Version {version} is available.": "版本 {version} 已推出。", + "{file} · {published}": "{file} · {published}", + "{info} · {size}": "{info} · {size}", + "Installing it will {action}.": "安裝時會{action}。", + "Last checked {when}": "上次檢查:{when}", + "{done} of {total} ({percent} %)": "{done} / {total}({percent} %)", + "{done} downloaded": "已下載 {done}", + "{file} is downloaded and checked; install it to update (the app restarts).": "已下載並檢查 {file};安裝即可更新(應用將重新啟動)。", "Color space: Rec. 2020 {curve} (HDR AVIF)": "色彩空間:Rec. 2020 {curve}(HDR AVIF)" } diff --git a/crates/ui-egui/locales/fork/zh-hant.json b/crates/ui-egui/locales/fork/zh-hant.json index 6cf8ffedaa..6546c2a7b5 100644 --- a/crates/ui-egui/locales/fork/zh-hant.json +++ b/crates/ui-egui/locales/fork/zh-hant.json @@ -1256,6 +1256,25 @@ "is in this week": "在本週", "is in this month": "在本月", "is in this year": "在今年", + "Check for Updates…": "檢查更新…", + "Install Update and Relaunch": "安裝更新並重新啟動", + "Checking for updates…": "正在檢查更新…", + "This is the newest version.": "已是最新版本。", + "The download is checked against the release's SHA-256 before anything is installed.": "安裝前會以發佈的 SHA-256 檢查下載內容。", + "The download is checked against the size the release states.": "下載會按發佈標明的大小檢查。", + "This build has no updates of its own: the releases page has the files for the platforms we ship.": "此構建沒有自帶更新:我們發佈的平台檔案在發佈頁上。", + "Open the releases page": "開啟發佈頁", + "Cancel Download": "取消下載", + "The download could not be finished.": "無法完成下載。", + "The download was cancelled.": "已取消下載。", + "Quit the app to let the installer finish.": "退出應用後安裝程式將完成。", + "Check Again": "再檢查一次", + "Download": "下載", + "Install and Relaunch": "安裝並重新啟動", + "Skip This Version": "跳過此版本", + "Check for updates when the app starts": "啟動時檢查更新", + "Include prereleases (release candidates)": "包含預發版(RC)", + "These settings are saved in the app's settings folder.": "這些設定保存在應用的設定資料夹中。", "File date": "檔案日期", "HDR curve": "HDR 曲線" } diff --git a/crates/ui-egui/src/i18n.rs b/crates/ui-egui/src/i18n.rs index 30ecca7599..4717eac5e3 100644 --- a/crates/ui-egui/src/i18n.rs +++ b/crates/ui-egui/src/i18n.rs @@ -476,6 +476,30 @@ mod tests { } } + /// The fork's own catalogs (`locales/fork/*.json`) are read by `build.rs` at compile time, so a + /// merge that mangles one fails the build with a JSON error. This says which file, and what is + /// wrong with it, in the test that already knows the name. + #[test] + fn fork_catalogs_are_valid_json() { + let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("locales").join("fork"); + let mut seen = 0; + for entry in std::fs::read_dir(&dir).expect("locales/fork") { + let path = entry.expect("a catalog").path(); + if path.extension().is_none_or(|e| e != "json") { + continue; + } + seen += 1; + let text = std::fs::read_to_string(&path).unwrap_or_else(|e| panic!("{}: {e}", path.display())); + let messages: std::collections::BTreeMap = + serde_json::from_str(&text).unwrap_or_else(|e| panic!("{}: {e}", path.display())); + assert!(!messages.is_empty(), "{}: no messages", path.display()); + for (key, value) in &messages { + assert!(!key.is_empty() && !value.is_empty(), "{}: empty message for {key:?}", path.display()); + } + } + assert!(seen >= 2, "found only {seen} fork catalog(s) in {}", dir.display()); + } + /// Where two catalogs translate the same text they agree on its placeholders. Catalogs may cover /// different sets of messages (a message a language lacks shows in English): the gaps are /// reported, not failed, so a translation can grow at its own pace. diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 1099243eeb..4b54d88924 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -158,6 +158,8 @@ mod tests_sync; mod tests_titlebar; #[cfg(test)] mod tests_unsaved; +#[cfg(all(test, not(target_arch = "wasm32")))] +mod tests_update; #[cfg(test)] mod tests_wb_selector; #[cfg(test)] @@ -463,6 +465,9 @@ pub struct LccApp { pub map: map::MapUi, /// The Classic module help sheet (⌘/, P6.3). pub help: help_overlay::HelpOverlay, + /// A dialog panel asked to be closed (it cannot do it itself: the dialog frame writes the state + /// back after the body has drawn). Taken by the dialog frame each frame. + pub close_dialog: bool, } impl LccApp { @@ -476,6 +481,7 @@ impl LccApp { print: Default::default(), map: Default::default(), help: Default::default(), + close_dialog: false, ui: UiState::default(), services, renderer: render::Renderer::default(), @@ -1092,6 +1098,8 @@ impl LccApp { import::tick(self, ctx); lightroom_import::tick(self, ctx); tasks::poll(self, ctx); + #[cfg(not(target_arch = "wasm32"))] + panels::update::poll(self, ctx); self.preview_build_status(ctx); self.save_status(ctx); self.slideshow_tick(ctx); diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index 373de9674a..496d87ddc7 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -233,6 +233,8 @@ pub const UI_COMMANDS: &[UiCommand] = &[ ("app.displayProfile", "Display Profile", None, ""), ("app.lensDbFolder", "Choose Lens Database Folder…", None, ""), ("app.about", "About {app}", None, "Help"), + ("app.checkForUpdates", "Check for Updates…", None, "Help"), + ("app.installUpdate", "Install Update and Relaunch", None, "Help"), ("app.systemInfo", "System Info…", None, "Help"), ("app.openLogFolder", "Open Log Folder", None, "Help"), ("app.whatsNew", "What's New", None, "Help"), @@ -1276,6 +1278,42 @@ pub fn run_ui_command(app: &mut LccApp, id: &str, p: &Value) -> Option Err("the web build updates by reloading the page".into()), + #[cfg(not(target_arch = "wasm32"))] + "app.checkForUpdates" => { + // open the dialog and ask the feed: the check runs on a worker thread, so the window + // appears at once and says "Checking…" while it waits + app.ui.dialog = Some(Dialog::Update); + match app.session.execute("update.check", &json!({})) { + Ok(_) => Ok(app.session.updater.status()), + // a check that cannot even be started shows why in the dialog + Err(e) => Err(e.to_string()), + } + } + #[cfg(target_arch = "wasm32")] + "app.installUpdate" => Err("the web build updates by reloading the page".into()), + #[cfg(not(target_arch = "wasm32"))] + "app.installUpdate" => { + // the same install the dialog's button runs, without the plan in front of it + match app.session.execute("update.install", &json!({"confirm": true})) { + Ok(v) => { + if let Some(message) = v["message"].as_str() { + app.toast(&ctx, message); + } + if v["exit"].as_bool().unwrap_or(false) { + ctx.send_viewport_cmd(egui::ViewportCommand::Close); + } + Ok(v) + } + // nothing downloaded yet: open the dialog, which explains what to do + Err(e) => { + app.ui.dialog = Some(Dialog::Update); + Err(e.to_string()) + } + } + } "photo.editInPhotoCraft" => edit_in(app, &ctx, p, true), "photo.editInExternal" => { // a PSD or TIFF: ask Edit Original / a Copy / a Copy with Adjustments first, as Lightroom does @@ -1879,6 +1917,11 @@ pub fn ui_enabled(app: &LccApp, id: &str) -> bool { app.session.active().is_some() } "photo.tagFromTracklog" => app.session.active().is_some() && app.services.pick_tracklog.is_some(), + // nothing downloaded, nothing to install (the dialog's own button says the same) + #[cfg(target_arch = "wasm32")] + "app.installUpdate" => false, + #[cfg(not(target_arch = "wasm32"))] + "app.installUpdate" => app.session.updater.staged().is_some(), "photo.editInPhotoCraft" | "photo.editInExternal" => app.session.active().is_some() && app.services.open_with.is_some(), "app.exportPrevious" => app.session.active().is_some() && app.session.last_export.is_some(), "dialog.pasteSettings" => app.session.active().is_some() && app.session.clipboard.is_some(), diff --git a/crates/ui-egui/src/panels/dialogs.rs b/crates/ui-egui/src/panels/dialogs.rs index e2d0fbfbf1..db514a15b0 100644 --- a/crates/ui-egui/src/panels/dialogs.rs +++ b/crates/ui-egui/src/panels/dialogs.rs @@ -258,6 +258,7 @@ pub fn show(app: &mut LccApp, ctx: &egui::Context) { Dialog::SamModel { .. } if sam_by_hand(&app.session.segmenter) => "Install the SAM 3 Model", Dialog::SamModel { .. } => "Download the SAM 3 Model?", Dialog::About => "About {app}", + Dialog::Update => "Check for Updates", Dialog::Shortcuts => "Keyboard Shortcuts", Dialog::ViewOptions => "Library View Options", } @@ -279,6 +280,7 @@ pub fn show(app: &mut LccApp, ctx: &egui::Context) { Dialog::Import { .. } => crate::import::DIALOG_SIZE[0], Dialog::SmartRules { .. } => 680.0, Dialog::AllMetadata { .. } => 620.0, + Dialog::Update => 500.0, Dialog::FaceModel { .. } => 460.0, Dialog::LightroomCatalog { .. } => 440.0, _ => 380.0, @@ -1218,6 +1220,13 @@ pub fn show(app: &mut LccApp, ctx: &egui::Context) { } Dialog::Shortcuts => crate::panels::keymap::body(app, ui, &t), Dialog::ViewOptions => crate::panels::cells::view_options(app, ui), + #[cfg(not(target_arch = "wasm32"))] + Dialog::Update => crate::panels::update::body(app, ui), + // the updater is native only; the web build has nothing to show here + #[cfg(target_arch = "wasm32")] + Dialog::Update => { + ui.label(crate::i18n::tr("The web build updates by reloading the page.")); + } }; if import { body(ui); @@ -1240,6 +1249,8 @@ pub fn show(app: &mut LccApp, ctx: &egui::Context) { | Dialog::SystemInfo { .. } | Dialog::AllMetadata { .. } | Dialog::WhatsNew + // the updater has its own buttons in the body; the footer only closes + | Dialog::Update ); let sam = &app.session.segmenter; let (sam_installed, sam_running, sam_failed) = (sam.installed(), sam.download_status().running, sam.download_status().error.is_some()); @@ -1288,6 +1299,8 @@ pub fn show(app: &mut LccApp, ctx: &egui::Context) { Dialog::SamModel { .. } if sam_installed || sam_running || sam_nowhere => "", Dialog::SamModel { error, .. } if error.is_some() || sam_failed => "Try Again", Dialog::SamModel { .. } => "Download", + // the updater's own buttons are in its body; the footer only closes + Dialog::Update => "", _ if informational => "Close", _ => "OK", }; @@ -1374,6 +1387,10 @@ pub fn show(app: &mut LccApp, ctx: &egui::Context) { if app.ui.dialog.as_ref().is_some_and(|now| *now != at_start) { return; } + // a panel inside the dialog asked to close it (its own Close or Skip button) + if std::mem::take(&mut app.close_dialog) { + close = true; + } app.ui.dialog = if close { None } else { Some(dlg) }; } @@ -1724,7 +1741,7 @@ pub fn confirm_dialog(app: &mut LccApp, dlg: &Dialog) -> Result app.run("library.removeFolder", json!({"path": path, "disk": disk})), d @ Dialog::SynchronizeFolder { .. } => crate::sync::confirm(app, d), - Dialog::About | Dialog::Shortcuts | Dialog::ViewOptions | Dialog::Settings { .. } => Ok(serde_json::Value::Null), + Dialog::About | Dialog::Shortcuts | Dialog::ViewOptions | Dialog::Settings { .. } | Dialog::Update => Ok(serde_json::Value::Null), } } diff --git a/crates/ui-egui/src/panels/mod.rs b/crates/ui-egui/src/panels/mod.rs index 837003d280..22f4476d00 100644 --- a/crates/ui-egui/src/panels/mod.rs +++ b/crates/ui-egui/src/panels/mod.rs @@ -45,6 +45,8 @@ pub mod strip; pub mod tether_bar; pub mod topbar; pub mod unnamed; +#[cfg(not(target_arch = "wasm32"))] +pub mod update; use egui::{Align2, Rect, pos2, vec2}; diff --git a/crates/ui-egui/src/panels/update.rs b/crates/ui-egui/src/panels/update.rs new file mode 100644 index 0000000000..040d5b2525 --- /dev/null +++ b/crates/ui-egui/src/panels/update.rs @@ -0,0 +1,325 @@ +//! Help ▸ Check for Updates…: the auto updater's face ([`lcc_engine::update`]). +//! +//! The dialog is the whole flow in one window: what this build is, whether a newer release exists, +//! what it says, and what the user can do about it — download it, install it and restart, or skip +//! this version. The updater's state lives in the session (a check runs on a worker thread), so the +//! window only reads `update.status` and dispatches `update.*`: nothing here has to survive a frame. +//! +//! Unless the user turns it off (the checkbox in the dialog, saved in the app's own settings +//! folder), one check runs shortly after the app starts. It never opens the dialog by itself: a +//! found release is announced with a toast, so a start does not interrupt whatever the user is +//! doing. + +use serde_json::{Value, json}; + +use crate::LccApp; +use crate::i18n::{tr, tr_format}; +use crate::state::Dialog; +use crate::theme::Tokens; +use crate::widgets::register; + +/// How long after start-up the automatic check runs (the app is busy opening the library). +const STARTUP_DELAY_S: f64 = 4.0; + +/// How often a running check or download asks to be redrawn. +const TICK_MS: u64 = 200; + +/// Pump the updater once a frame: the start-up check, the worker's result, and a repaint while +/// something is in flight. +pub fn poll(app: &mut LccApp, ctx: &egui::Context) { + if app.session.updater.poll() { + // what the dialog shows just changed (a check's answer, a download's outcome) + ctx.request_repaint(); + } + let now = ctx.input(|i| i.time); + if app.session.updater.checking() || app.session.updater.downloading() { + ctx.request_repaint_after(std::time::Duration::from_millis(TICK_MS)); + } + if !app.ui.update_checked_at_startup { + app.ui.update_checked_at_startup = true; + if app.session.updater.prefs().check_at_startup { + app.ui.update_checked_at = now + STARTUP_DELAY_S; + } + } + if app.ui.update_checked_at > 0.0 && now >= app.ui.update_checked_at { + app.ui.update_checked_at = 0.0; + let _ = app.session.execute("update.check", &json!({})); + } + // a start-up check that found something says so once, without opening a window + if let Some(version) = app.ui.update_pending.clone() + && let Some(available) = app.session.updater.available() + && available.version == version + { + app.ui.update_pending = None; + app.toast(ctx, tr_format!("{app} {version} is available (Help ▸ Check for Updates…)", version = version)); + } + // a staged file whose release is no longer on offer (a newer check replaced it) leaves nothing behind + if app.session.updater.available().is_none() + && let Some(staged) = app.session.updater.staged().cloned() + && !matches!(app.ui.dialog, Some(Dialog::Update)) + { + lcc_engine::update::discard(&staged); + app.session.updater.set_progress(lcc_engine::update::Progress::Idle); + } +} + +/// The dialog's body (the window frame is [`crate::panels::dialogs`]'s). +pub fn body(app: &mut LccApp, ui: &mut egui::Ui) { + let t = Tokens::get(ui.ctx()); + let status = app.session.updater.status(); + let version = status["version"].as_str().unwrap_or_default().to_string(); + let platform = status["platform"].as_str().unwrap_or_default().to_string(); + let supported = status["supported"].as_bool().unwrap_or(false); + ui.set_min_width(460.0); + + ui.horizontal(|ui| { + ui.label(egui::RichText::new(tr_format!("{app} {version}", version = version)).font(t.semibold(13.5)).color(t.text)); + ui.label(egui::RichText::new(platform).font(t.font(11.5)).color(t.text_dim)); + }); + + if !supported { + ui.add_space(6.0); + ui.label( + egui::RichText::new(tr("This build has no updates of its own: the releases page has the files for the platforms we ship.")) + .color(t.text_dim), + ); + if link(ui, "link:updateReleases", tr("Open the releases page")) { + let _ = crate::links::open(app, &format!("{}/releases", lcc_brand::REPOSITORY)); + } + settings(app, ui, &t); + return; + } + + let check = status["check"].as_str().unwrap_or("never"); + let download = status["download"].as_str().unwrap_or("idle"); + ui.add_space(8.0); + match check { + "running" => { + ui.horizontal(|ui| { + ui.spinner(); + ui.label(egui::RichText::new(tr("Checking for updates…")).color(t.text_label)); + }); + } + "found" => { + let a = &status["available"]; + let found = a["version"].as_str().unwrap_or_default().to_string(); + ui.label(egui::RichText::new(tr_format!("Version {version} is available.", version = found)).font(t.semibold(13.0)).color(t.text)); + let mut line = a["file"].as_str().unwrap_or_default().to_string(); + if let Some(published) = a["published"].as_str() { + line = tr_format!("{file} · {published}", file = line, published = published); + } + if let Some(size) = a["size"].as_u64().filter(|s| *s > 0) { + line = tr_format!("{info} · {size}", info = line, size = megabytes(size)); + } + ui.label(egui::RichText::new(line).font(t.font(11.5)).color(t.text_dim)); + if let Some(action) = a["action"].as_str() { + ui.label(egui::RichText::new(tr_format!("Installing it will {action}.", action = action)).color(t.text_label)); + } + ui.label( + egui::RichText::new(if a["verified"].as_bool().unwrap_or(false) { + tr("The download is checked against the release's SHA-256 before anything is installed.") + } else { + tr("The download is checked against the size the release states.") + }) + .font(t.font(11.0)) + .color(t.text_dim), + ); + let notes = a["notes"].as_str().unwrap_or("").trim().to_string(); + if !notes.is_empty() { + ui.add_space(4.0); + egui::ScrollArea::vertical() + .id_salt("update-notes") + .max_height(crate::panels::dialogs::list_height(ui, 220.0)) + .auto_shrink([false, true]) + .show(ui, |ui| notes_body(ui, &t, ¬es)); + } + } + _ => { + let last = status["lastChecked"].as_str().unwrap_or_default().to_string(); + ui.label(egui::RichText::new(tr("This is the newest version.")).color(t.text_label)); + if !last.is_empty() { + ui.label(egui::RichText::new(tr_format!("Last checked {when}", when = last)).font(t.font(11.5)).color(t.text_dim)); + } + } + } + + // the download and the install + ui.add_space(8.0); + match download { + "running" => { + let bytes = status["progress"]["bytes"].as_u64().unwrap_or(0); + let total = status["progress"]["total"].as_u64().unwrap_or(0); + let frac = if total > 0 { (bytes as f64 / total as f64).clamp(0.0, 1.0) as f32 } else { 0.0 }; + let text = if total > 0 { + tr_format!( + "{done} of {total} ({percent} %)", + done = megabytes(bytes), + total = megabytes(total), + percent = (frac * 100.0).round() as u64 + ) + } else { + tr_format!("{done} downloaded", done = megabytes(bytes)) + }; + let r = ui.add(egui::ProgressBar::new(frac).text(text)); + register(ui.ctx(), "progress:updateDownload", r.rect); + if button(ui, "button:updateCancel", tr("Cancel Download")) { + let _ = app.session.execute("update.downloadCancel", &json!({})); + } + } + "ready" => { + let staged = &status["staged"]; + ui.label( + egui::RichText::new(tr_format!( + "{file} is downloaded and checked; install it to update (the app restarts).", + file = staged["file"].as_str().unwrap_or_default() + )) + .color(t.text_label), + ); + } + "failed" => { + ui.label(egui::RichText::new(tr("The download could not be finished.")).color(t.text)); + if let Some(why) = status["error"].as_str() { + ui.label(egui::RichText::new(why).font(t.font(11.5)).color(t.text_dim)); + } + } + "cancelled" => { + ui.label(egui::RichText::new(tr("The download was cancelled.")).color(t.text_dim)); + } + _ => {} + } + + // a failed check explains itself + if check == "never" + && let Some(why) = status["error"].as_str() + { + ui.label(egui::RichText::new(why).font(t.font(11.5)).color(t.text_dim)); + } + + if let Some(installed) = status.get("installed") { + ui.add_space(4.0); + ui.label(egui::RichText::new(installed["message"].as_str().unwrap_or_default()).color(t.text_label)); + if installed["exit"].as_bool().unwrap_or(false) { + ui.label(egui::RichText::new(tr("Quit the app to let the installer finish.")).font(t.font(11.5)).color(t.text_dim)); + } + } + + // the buttons + ui.add_space(10.0); + let checking = check == "running"; + let downloading = download == "running"; + let ready = download == "ready"; + ui.horizontal(|ui| { + if button(ui, "button:updateCheck", tr("Check Again")) && !checking { + let _ = app.session.execute("update.check", &json!({})); + } + if check == "found" && !ready && !downloading && button(ui, "button:updateDownload", tr("Download")) { + let _ = app.session.execute("update.download", &json!({})); + } + if ready && button(ui, "button:updateInstall", tr("Install and Relaunch")) { + match app.session.execute("update.install", &json!({"confirm": true})) { + Ok(v) => { + if let Some(message) = v["message"].as_str() { + app.toast(ui.ctx(), message); + } + if v["exit"].as_bool().unwrap_or(false) { + // the installer or the replacement script needs this process gone + ui.ctx().send_viewport_cmd(egui::ViewportCommand::Close); + } + } + Err(e) => app.toast(ui.ctx(), e.to_string()), + } + } + if check == "found" + && let Some(version) = status["available"]["version"].as_str() + && button(ui, "button:updateSkip", tr("Skip This Version")) + { + // the dialog stays open (its own Close or Esc ends it); this only stops the asking + let _ = app.session.execute("update.dismiss", &json!({"version": version, "skipped": true})); + } + }); + + settings(app, ui, &t); +} + +/// The two settings, and where the download lands. +fn settings(app: &mut LccApp, ui: &mut egui::Ui, t: &Tokens) { + ui.add_space(8.0); + ui.separator(); + let mut check_at_startup = app.session.updater.prefs().check_at_startup; + let mut prerelease = app.session.updater.prefs().prerelease; + let r = ui.checkbox(&mut check_at_startup, tr("Check for updates when the app starts")); + register(ui.ctx(), "check:updateAtStartup", r.rect); + let r = ui.checkbox(&mut prerelease, tr("Include prereleases (release candidates)")); + register(ui.ctx(), "check:updatePrerelease", r.rect); + if check_at_startup != app.session.updater.prefs().check_at_startup || prerelease != app.session.updater.prefs().prerelease { + let _ = app.session.execute("update.prefs", &json!({"checkAtStartup": check_at_startup, "prerelease": prerelease})); + } + if !app.session.updater.persistent() { + ui.label(egui::RichText::new(tr("These settings are saved in the app's settings folder.")).font(t.font(11.0)).color(t.text_dim)); + } +} + +/// The release notes: the app's Markdown subset (`### Heading`, `- item`, prose). +fn notes_body(ui: &mut egui::Ui, t: &Tokens, notes: &str) { + ui.scope(|ui| { + for line in notes.lines().take(400) { + let l = line.trim_end(); + if let Some(h) = l.strip_prefix("### ") { + ui.add_space(4.0); + ui.label(egui::RichText::new(crate::i18n::tr(h)).font(t.semibold(12.5)).color(t.text)); + } else if let Some(h) = l.strip_prefix("## ") { + ui.add_space(6.0); + ui.label(egui::RichText::new(crate::i18n::tr(h)).font(t.semibold(13.5)).color(t.text)); + } else if l.starts_with("# ") || l.is_empty() { + } else if let Some(b) = l.strip_prefix("- ") { + ui.label(egui::RichText::new(format!("• {}", crate::i18n::tr(b).replace('`', ""))).color(t.text_label)); + } else { + ui.label(egui::RichText::new(crate::i18n::tr(l.trim()).replace('`', "")).color(t.text_label)); + } + } + }); +} + +/// `12.3 MB`. +fn megabytes(bytes: u64) -> String { + let mb = bytes as f64 / 1_048_576.0; + if mb < 10.0 { format!("{mb:.1} MB") } else { format!("{:.0} MB", mb.floor()) } +} + +fn button(ui: &mut egui::Ui, id: &str, label: &str) -> bool { + let r = ui.button(label); + register(ui.ctx(), id, r.rect); + r.clicked() +} + +fn link(ui: &mut egui::Ui, id: &str, label: &str) -> bool { + let r = ui.link(label); + register(ui.ctx(), id, r.rect); + r.clicked() +} + +/// What `update.status` says, for the control channel and tests. +pub fn status(app: &LccApp) -> Value { + app.session.updater.status() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn megabytes_are_worded() { + assert_eq!(megabytes(0), "0.0 MB"); + assert_eq!(megabytes(1_048_576), "1.0 MB"); + assert_eq!(megabytes(150 * 1_048_576), "150 MB"); + } + + #[test] + fn a_status_snapshot_has_the_fields_the_dialog_reads() { + let app = LccApp::new(lcc_engine::Session::new(), crate::Services::default()); + let v = status(&app); + for key in ["version", "platform", "supported", "check", "download", "checkAtStartup", "prerelease", "repo", "page"] { + assert!(v.get(key).is_some(), "{key} is missing from {v}"); + } + } +} diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index 2b84c6c983..3c4ec809cb 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -824,6 +824,15 @@ pub struct UiState { /// A Settings section to bring into view once (`app.settings {section}`), e.g. `lensProfiles`. #[serde(skip)] pub settings_section: Option, + /// The start-up update check has run (once per session; Help ▸ Check for Updates… is manual). + #[serde(skip)] + pub update_checked_at_startup: bool, + /// When an update check was last started (egui time, s). + #[serde(skip)] + pub update_checked_at: f64, + /// A newer release was found at start-up and the user has not been told yet. + #[serde(skip)] + pub update_pending: Option, } /// Settings group ids (`SettingsGroup` serde names) a new preset includes by default: everything @@ -998,6 +1007,9 @@ pub enum Dialog { SystemInfo { rows: Vec<(String, String)>, }, + /// Help ▸ Check for Updates…: the release feed's answer, the download and the install + /// (the panel state lives in the session's updater; see [`crate::panels::update`]). + Update, /// Every metadata field of a photo's file (`photo.allMetadata`), filtered by `search`. AllMetadata { title: String, @@ -1260,6 +1272,9 @@ impl Default for UiState { status: String::new(), dialog: None, settings_section: None, + update_checked_at_startup: false, + update_checked_at: 0.0, + update_pending: None, } } } diff --git a/crates/ui-egui/src/tests_update.rs b/crates/ui-egui/src/tests_update.rs new file mode 100644 index 0000000000..cc095f892d --- /dev/null +++ b/crates/ui-egui/src/tests_update.rs @@ -0,0 +1,225 @@ +//! Help ▸ Check for Updates… in the app (see `lcc_engine::update`). +//! +//! Scenarios, in the words of someone updating: +//! +//! * Help ▸ Check for Updates… opens the dialog, which shows this build and asks the release feed. +//! * A newer release is listed with its file, size, install action and notes, and it can be +//! downloaded, installed or skipped. +//! * Skipping remembers the version, so a start-up check does not ask about it again. +//! * The two settings are in the dialog and are saved. +//! * An install that only lays the file out never quits the app, and says what to do instead. +//! +//! The fixtures (a scratch folder, a fake downloaded file) are set up the short way this crate's +//! other UI tests use: a failed `unwrap` there fails the test, which is the point. +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +use std::path::PathBuf; +use std::time::Duration; + +use serde_json::json; + +use crate::headless::Headless; +use crate::state::Dialog; +use crate::{LccApp, Services}; + +const T: Duration = Duration::from_secs(20); + +/// A scratch folder that goes away with the test, however it ends. +struct Scratch(PathBuf); + +impl Scratch { + fn new(tag: &str) -> Scratch { + let dir = std::env::temp_dir().join(format!("lc-ui-update-{tag}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + Scratch(dir) + } +} + +impl Drop for Scratch { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} + +fn ask(h: &mut Headless, method: &str, params: serde_json::Value) -> serde_json::Value { + let r = h.request(method, params, T); + assert_eq!(r["ok"], true, "{method}: {r}"); + r +} + +/// The PNG encoder and file writer a real host provides (`ui.screenshot` needs them). +fn services() -> Services { + Services { + png: Some(Box::new(|img: &lcc_raster::Rgba8| { + lcc_codecs::encode_png(&lcc_codecs::EncodeImage::rgba8(img), &lcc_codecs::EncodeMeta::default()).unwrap_or_default() + })), + write: Some(Box::new(|p: &str, b: &[u8]| std::fs::write(p, b).map_err(|e| e.to_string()))), + ..Default::default() + } +} + +/// The app with an in-memory session (no library, no network) and the start-up check already done. +fn app() -> Headless { + let mut session = lcc_engine::Session::new(); + // a fresh updater: the settings are the defaults, not whatever this machine's are + session.updater = lcc_engine::update::Updater::new(None); + let app = LccApp::new(session, services()); + let mut h = Headless::new(app, [1200.0, 900.0], 1.0); + // no start-up check: these tests drive the dialog themselves + h.app.ui.update_checked_at_startup = true; + h.step(); + h +} + +/// Offer `version` as a newer release, as a check would, with its file already downloaded. +fn offer(h: &mut Headless, dir: &Scratch, version: &str, kind: lcc_engine::update::Kind) -> PathBuf { + use lcc_engine::update::{Kind, Progress, Staged}; + let file = dir.0.join(format!("app-{version}-{}.bin", kind.text())); + std::fs::write(&file, b"an installer").unwrap(); + let engine_kind = match kind { + Kind::Msi => lcc_updater::Kind::Msi, + Kind::Dmg => lcc_updater::Kind::Dmg, + Kind::AppImage => lcc_updater::Kind::AppImage, + Kind::Archive => lcc_updater::Kind::Archive, + Kind::Checksums => lcc_updater::Kind::Checksums, + }; + let name = file.file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_default(); + let update = lcc_updater::Update { + current: lcc_updater::Version::current(), + version: lcc_updater::Version::parse(version).unwrap(), + title: format!("App {version}"), + tag: format!("v{version}"), + asset: lcc_updater::Asset { name: name.clone(), url: "http://127.0.0.1:1/app.bin".into(), size: 12, sha256: None, kind: engine_kind }, + sha256: Some("ab".repeat(32)), + published: Some("2026-10-12".into()), + notes: "### Fixed\n- a thing".into(), + action: "run the installer".into(), + }; + h.app.session.updater.apply(lcc_updater::Checked::Found(Box::new(update))); + h.app.session.updater.set_progress(Progress::Ready(Box::new(Staged { + version: version.into(), + path: file.clone(), + bytes: 12, + sha256: "ab".repeat(32), + file: name, + kind, + notes: "### Fixed\n- a thing".into(), + }))); + file +} + +#[test] +fn the_help_menu_opens_the_dialog_and_it_lists_what_is_available() { + let dir = Scratch::new("listing"); + let mut h = app(); + let _ = offer(&mut h, &dir, "9.9.9", lcc_engine::update::Kind::Archive); + ask(&mut h, "ui.menu.invoke", json!({"id": "app.checkForUpdates"})); + h.step(); + assert_eq!(h.app.ui.dialog, Some(Dialog::Update), "the dialog is up"); + // Esc closes the dialog (the window's own Close is registered as the frame's) + assert!(h.app.widgets.iter().any(|(w, _)| w == "dialog:window"), "the window is laid out"); + assert!(h.app.widgets.iter().any(|(w, _)| w == "button:updateCheck")); + assert!(h.app.widgets.iter().any(|(w, _)| w == "button:updateInstall"), "a downloaded file can be installed"); + assert!(h.app.widgets.iter().any(|(w, _)| w == "button:updateSkip")); + assert!(h.app.widgets.iter().any(|(w, _)| w == "check:updateAtStartup")); + assert!(h.app.widgets.iter().any(|(w, _)| w == "check:updatePrerelease")); + let text = h.painted_text().join(" "); + assert!(text.contains("9.9.9"), "the version is shown: {text}"); + assert!(text.contains("is available"), "{text}"); + // Esc ends it, like the other dialogs that only show something + h.request("ui.key", json!({"key": "Escape"}), T); + h.step(); + assert_eq!(h.app.ui.dialog, None, "Esc closes the dialog"); +} + +#[test] +fn a_startup_check_that_found_a_release_waits_until_the_dialog_is_opened() { + let dir = Scratch::new("startup"); + let mut h = app(); + // as the start-up path does: the worker's answer is pending, and no window opened by itself + h.app.ui.update_pending = Some("9.9.9".into()); + let _ = offer(&mut h, &dir, "9.9.9", lcc_engine::update::Kind::Archive); + h.step(); + h.step(); + assert_eq!(h.app.ui.dialog, None, "a start-up check never opens a window"); + assert!(h.app.ui.update_pending.is_none(), "the announcement is made once"); + assert!(h.app.ui.toast.is_some(), "it says so instead"); +} + +#[test] +fn a_manual_install_never_quits_the_app() { + let dir = Scratch::new("manual"); + let mut h = app(); + let file = offer(&mut h, &dir, "9.9.9", lcc_engine::update::Kind::Archive); + ask(&mut h, "ui.menu.invoke", json!({"id": "app.checkForUpdates"})); + h.step(); + // the archive path is a manual install: it shows the file and stays open + h.request("ui.clickWidget", json!({"id": "button:updateInstall"}), T); + h.step(); + assert!(!h.quit_requested(), "nothing to quit for"); + assert_eq!(h.app.ui.dialog, Some(Dialog::Update)); + assert!(file.exists(), "the downloaded file is still there for the user to unpack"); + let installed = h.app.session.updater.installed().expect("an outcome"); + assert!(!installed.exit); + assert!(installed.message.contains("Quit the app"), "{}", installed.message); +} + +#[test] +fn skipping_remembers_the_version() { + let dir = Scratch::new("skip"); + let mut h = app(); + let _ = offer(&mut h, &dir, "9.9.9", lcc_engine::update::Kind::Archive); + ask(&mut h, "ui.menu.invoke", json!({"id": "app.checkForUpdates"})); + h.step(); + ask(&mut h, "ui.clickWidget", json!({"id": "button:updateSkip"})); + h.step(); + assert!(h.app.session.updater.already_seen("9.9.9"), "the version is remembered"); + // the dialog stays open until it is closed, and the update is no longer announced as new + assert_eq!(h.app.ui.dialog, Some(Dialog::Update)); + h.request("ui.key", json!({"key": "Escape"}), T); + h.step(); + assert_eq!(h.app.ui.dialog, None, "Esc ends the dialog"); +} + +#[test] +fn the_settings_in_the_dialog_are_saved() { + let mut h = app(); + ask(&mut h, "ui.menu.invoke", json!({"id": "app.checkForUpdates"})); + h.step(); + assert!(h.app.session.updater.prefs().check_at_startup, "on by default"); + ask(&mut h, "ui.clickWidget", json!({"id": "check:updateAtStartup"})); + h.step(); + assert!(!h.app.session.updater.prefs().check_at_startup, "turning it off is saved"); + ask(&mut h, "ui.clickWidget", json!({"id": "check:updatePrerelease"})); + h.step(); + assert!(h.app.session.updater.prefs().prerelease); + // the dialog is still usable after a settings change + assert_eq!(h.app.ui.dialog, Some(Dialog::Update)); + h.request("ui.key", json!({"key": "Escape"}), T); + h.step(); + assert_eq!(h.app.ui.dialog, None); +} + +#[test] +fn the_download_button_says_it_cannot_start_when_there_is_nothing_to_fetch() { + let mut h = app(); + ask(&mut h, "ui.menu.invoke", json!({"id": "app.checkForUpdates"})); + h.step(); + // nothing on offer: no Download button is drawn at all + assert!(h.app.widgets.iter().all(|(w, _)| w != "button:updateDownload"), "no update, no Download"); + // and the command says why rather than panicking + let r = h.app.session.execute("update.download", &json!({})); + assert!(r.is_err()); +} + +#[test] +fn a_checksum_list_is_never_offered_for_install() { + let dir = Scratch::new("sums"); + let mut h = app(); + let _ = offer(&mut h, &dir, "9.9.9", lcc_engine::update::Kind::Checksums); + ask(&mut h, "ui.menu.invoke", json!({"id": "app.checkForUpdates"})); + h.step(); + let err = h.app.session.execute("update.install", &json!({"confirm": true})).expect_err("refused"); + assert!(err.to_string().contains("no file for this system"), "{err}"); +} diff --git a/crates/updater/Cargo.toml b/crates/updater/Cargo.toml new file mode 100644 index 0000000000..9cc0481790 --- /dev/null +++ b/crates/updater/Cargo.toml @@ -0,0 +1,18 @@ +[package] +name = "lcc-updater" +version.workspace = true +edition.workspace = true +license.workspace = true +description = "Auto updater (L0): GitHub Releases feed, platform asset selection, verified download, staged install" + +[lints] +workspace = true + +# Native only: the web build updates by reloading the page (the crate is empty on wasm32). +[dependencies] +lcc-brand = { workspace = true } +lcc-net = { workspace = true } +serde_json = { workspace = true } +sha2 = { workspace = true } +log = { workspace = true } + diff --git a/crates/updater/README.md b/crates/updater/README.md new file mode 100644 index 0000000000..fabcd38232 --- /dev/null +++ b/crates/updater/README.md @@ -0,0 +1,56 @@ +# lcc-updater + +The app's auto updater (L0, native only): it finds a newer release, downloads the file for this +machine, and stages installing it. There is no update service behind it — the release feed is a file +the release pipeline publishes, plus GitHub's own Releases API as a fallback. + +```rust +// what is newer than this build? +let opts = lcc_updater::Options::default(); // brand repository, this version, this platform +if let Some(update) = lcc_updater::check(&opts, None, None)? { + println!("{} → {}", update.current, update.version); // 0.7.0 → 0.8.0 + println!("{} ({})", update.asset.name, update.action); // the file, and what installing it does + // fetch it (resumable, size- and SHA-256-checked) into the cache folder + let got = lcc_updater::download(&update, &lcc_updater::client()?, dir, None, None)?; + // say what would happen, then do it (installs over the running installation) + let plan = lcc_updater::plan(update.asset.kind, &got.path, &update.version.to_text()); + let outcome = lcc_updater::install(update.asset.kind, &got, &update.version.to_text())?; + if outcome.exit { /* quit: the installer or the replacement script takes over */ } +} +``` + +- **The feed.** `latest.json` on the newest release (`…/releases/latest/download/latest.json`), + else `GET /repos/{owner}/{repo}/releases` (no token needed for a public repository; a 403 is the + rate limit, reported as such), else a URL the caller or `_UPDATE_URL` names. Both shapes + parse into `Release`; the newest **version** wins, not the feed's order. +- **Versions** are SemVer 2.0.0 (`v1.2.3`, `1.2.3-rc.1`); a tag that is not a version (`nightly`) is + not a release of ours. A prerelease is only offered when asked for, and a release outranks its own + prereleases. +- **The right file** is picked from the artifact names the pipeline already uses + (`---…`): the MSI on Windows, the DMG on macOS, the AppImage on Linux + x86_64/aarch64, and a tarball (or the portable zip) as a manual install anywhere else. An + installer always wins over an archive; the `SHA256SUMS.txt` asset is read for the hash, never + installed. +- **Downloads** resume from a `.part` file, are capped, and must match the size the feed states and + the SHA-256 the release publishes (the size alone when it publishes none) before they are renamed + into place. A file that fails its check is deleted. A file already there is re-hashed, not trusted + by name; a hostile asset name (`../../…`) is reduced to its last path segment. +- **Installing** is `install::plan` (what will happen, in words, before anything does) and + `install::install`: `msiexec` runs the Windows installer, a macOS script mounts the disk image and + copies the app over the running one from a terminal window, a Linux script renames the running + AppImage aside and starts the new one, and anything else is revealed in the file manager for a + manual unpack. Every path ends with the app running again or with a sentence saying what to do. +- **Never a panic.** No network, a rate-limited API, a release without a file for this machine, a + truncated download, a full disk, an installer that refuses: all are `UpdateError` values a dialog + can show, and all leave the current installation untouched. + +## Sources + +Own design, from the documented [GitHub Releases API](https://docs.github.com/rest/releases) and +the layout of release assets; version precedence follows [Semantic Versioning +2.0.0](https://semver.org/spec/v2.0.0.html). The shape of the flow (check → download → install and +restart, with a manifest beside the release) follows Tauri's updater as a design reference, not its +code. + +Tests use local HTTP servers for the feed, the checksum list and the file: they make no internet +requests. The end-to-end path (feed → download → staged file) is covered in `lcc-engine`. diff --git a/crates/updater/src/check.rs b/crates/updater/src/check.rs new file mode 100644 index 0000000000..5111423b96 --- /dev/null +++ b/crates/updater/src/check.rs @@ -0,0 +1,379 @@ +//! The update check itself: read the release feed, compare it with this build, pick the file. +//! +//! Nothing is downloaded here ([`crate::download`]) and nothing is installed ([`crate::install`]); +//! a check is one small HTTPS request that returns an [`Update`] describing what is newer, or +//! `None` when this build is current. +//! +//! Where the feed comes from, in order: +//! 1. the body the caller already has ([`check`]'s `feed`, which the engine fetches off the UI +//! thread and caches); +//! 2. [`Options::manifest_url`] (the `_UPDATE_URL` override, or a build that pins one); +//! 3. the static `latest.json` published on the newest release; +//! 4. GitHub's Releases API for the brand's repository ([`lcc_brand::REPOSITORY`]). +//! +//! The API needs no token for a public repository, but it is rate-limited per IP; a 403 there is +//! reported as such, and the static manifest is tried first because it is a plain file on the +//! release and keeps working when the API is rate-limited. + +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::{Arc, Mutex, PoisonError}; +use std::time::Duration; + +use lcc_net::{Client, ClientConfig}; + +use crate::error::UpdateError; +use crate::release::{self, Release}; +use crate::target::{Asset, Target}; +use crate::version::Version; + +/// Feed bodies are small; anything larger is not our release list. +const MAX_FEED_BYTES: u64 = 4 * 1024 * 1024; +/// Downloads can be a disk image or an installer: generous, but not unbounded. +pub const MAX_DOWNLOAD_BYTES: u64 = 4 * 1024 * 1024 * 1024; + +/// How long a finished check answers a repeat question without asking again. +pub const REUSE_AFTER: Duration = Duration::from_secs(20); + +/// What a check was told to do. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Options { + /// Repository to ask, `owner/name`. + pub repo: String, + /// The build to compare against (usually [`Version::current`]). + pub current: Version, + /// The machine's platform; `None` when we have no update for it. + pub target: Option, + /// Include prereleases (`-rc.1`) in what counts as newer. + pub prerelease: bool, + /// A feed URL that replaces the GitHub API (the `_UPDATE_URL` override, or the static + /// manifest a build was pointed at). + pub manifest_url: Option, +} + +impl Default for Options { + fn default() -> Self { + Options { + repo: lcc_brand::REPOSITORY.to_string(), + current: Version::current(), + target: Target::current(), + prerelease: false, + manifest_url: override_url(), + } + } +} + +/// `_UPDATE_URL`: point the updater at another feed (a local server, a mirror, a fork). +/// Read through the brand, so the legacy prefix still works. +pub fn override_url() -> Option { + lcc_brand::env("UPDATE_URL").map(|s| s.trim().to_string()).filter(|s| !s.is_empty()) +} + +/// A newer release, and the file this machine would install. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Update { + /// What is running now. + pub current: Version, + /// The newer release. + pub version: Version, + /// The release title (or its tag). + pub title: String, + pub tag: String, + /// The asset to download. + pub asset: Asset, + /// SHA-256 to check the download against, when the release publishes one. + pub sha256: Option, + /// `YYYY-MM-DD`, when the feed says. + pub published: Option, + /// The release notes (Markdown). + pub notes: String, + /// One line on what installing it will do on this machine. + pub action: String, +} + +impl Update { + /// The version as a dialog shows it (`1.2.3`). + pub fn version_text(&self) -> String { + self.version.to_text() + } +} + +/// Check for an update: `Ok(None)` when this build is the newest the feed knows of. +/// +/// `feed` is a release feed body the caller already has (the engine fetches and caches it, so a +/// check costs no request); `None` fetches it from [`Options::manifest_url`], the release's +/// `latest.json`, or the API. +pub fn check(opts: &Options, feed: Option<&str>, cancel: Option>) -> Result, UpdateError> { + let Some(target) = opts.target else { + return Err(UpdateError::Unsupported(format!( + "there is no update for this build ({} {}); the releases page has the files for the platforms we ship", + std::env::consts::OS, + std::env::consts::ARCH + ))); + }; + let body = match feed { + Some(text) => text.to_string(), + None => fetch_feed(opts, cancel.clone())?, + }; + let release = release::newest(&body, opts.prerelease)?; + from_release(opts, target, release, cancel) +} + +/// [`check`] for a release already parsed (a test, or a caller that cached the parse). +pub fn from_release(opts: &Options, target: Target, release: Release, cancel: Option>) -> Result, UpdateError> { + if release.version <= opts.current { + return Ok(None); + } + let Some(asset) = release.best_asset(&target).cloned() else { + return Err(UpdateError::NoAssetFor { version: release.version.to_text(), target: format!("{}-{}", target.os.slug(), target.arch) }); + }; + // the release's own checksum list, when it is not already in the feed entry + let sha256 = match &asset.sha256 { + Some(sha) => Some(sha.clone()), + None => match release.checksum_asset() { + Some(sums) => fetch_checksum(&sums.url, &asset.name, cancel)?, + None => None, + }, + }; + Ok(Some(Update { + current: opts.current.clone(), + version: release.version.clone(), + title: release.title.clone(), + tag: release.tag.clone(), + asset, + sha256, + published: release.published.clone(), + notes: release.notes.clone(), + action: target.describe(), + })) +} + +/// The feed body: the override URL, else the static manifest on the newest release, else the API. +fn fetch_feed(opts: &Options, cancel: Option>) -> Result { + if let Some(url) = &opts.manifest_url { + return get_text(url, cancel); + } + match get_text(&manifest_url(&opts.repo), cancel.clone()) { + Ok(body) => Ok(body), + // no manifest on that release (an older one, or none published yet): ask the API + Err(UpdateError::Http { code: 404, .. }) => get_text(&api_url(&opts.repo), cancel), + Err(e) => Err(e), + } +} + +/// `https://github.com///releases/latest/download/latest.json`. +pub fn manifest_url(repo: &str) -> String { + format!("https://github.com/{}/releases/latest/download/latest.json", repo.trim().trim_matches('/')) +} + +/// `https://api.github.com/repos///releases?per_page=30`. +pub fn api_url(repo: &str) -> String { + format!("https://api.github.com/repos/{}/releases?per_page=30", repo.trim().trim_matches('/')) +} + +fn client() -> Result { + Client::new(ClientConfig { + max_body: MAX_FEED_BYTES, + connect_timeout: Duration::from_secs(8), + stall_timeout: Duration::from_secs(20), + ..ClientConfig::default() + }) + .map_err(|e| UpdateError::Net(e.to_string())) +} + +/// GET a small text body. +fn get_text(url: &str, cancel: Option>) -> Result { + let client = client()?; + let mut req = client.get(url).header("Accept", "application/vnd.github+json, application/json"); + if let Some(flag) = cancel { + req = req.cancel(flag); + } + let resp = req.send()?; + let status = resp.status; + let body = resp.text()?; + if status == 403 || status == 429 { + // never the body: it can be a whole HTML page + let what = if body.contains("rate limit") { "GitHub's rate limit was reached; try again later" } else { "the feed refused the request" }; + return Err(UpdateError::Http { code: status, what: what.to_string() }); + } + if !(200..300).contains(&status) { + return Err(UpdateError::Http { code: status, what: "the release feed was not found".into() }); + } + Ok(body) +} + +/// The release's checksum list: the SHA-256 for `file`, when it lists it. +fn fetch_checksum(url: &str, file: &str, cancel: Option>) -> Result, UpdateError> { + // a checksum that cannot be fetched is not a failure: the download is still TLS-verified and + // size-checked, and saying "no update" because of a missing sums file would be worse + match get_text(url, cancel) { + Ok(body) => Ok(crate::checksum::lookup(&body, file)), + Err(e) => { + log::debug!("update: checksum list: {e}"); + Ok(None) + } + } +} + +/// The result of one check, for the UI and `update.status`. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Checked { + /// A newer release is available. + Found(Box), + /// This build is the newest the feed knows of. + Current(String), + /// The check failed. + Failed(String), +} + +/// A memo of the last check, so a dialog opened twice does not ask GitHub twice, and only one +/// check runs at a time. +#[derive(Default)] +pub struct Cache { + last: Mutex>, + running: AtomicBool, +} + +impl Cache { + /// The last result, when it is recent and was asked with the same options. + pub fn get(&self, opts: &Options) -> Option { + let guard = self.last.lock().unwrap_or_else(PoisonError::into_inner); + match guard.as_ref() { + Some((when, had, result)) if had == opts && when.elapsed() < REUSE_AFTER => Some(result.clone()), + _ => None, + } + } + + /// Record a result. + pub fn put(&self, opts: &Options, result: Checked) { + *self.last.lock().unwrap_or_else(PoisonError::into_inner) = Some((std::time::Instant::now(), opts.clone(), result)); + } + + /// Claim the single check slot (`false`: another one is already running). + pub fn begin(&self) -> bool { + !self.running.swap(true, Ordering::SeqCst) + } + + /// Release the single check slot. + pub fn end(&self) { + self.running.store(false, Ordering::SeqCst); + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::target::Os; + + fn opts() -> Options { + Options { + // the real repository, so the URL helpers are checked against what we publish to + repo: lcc_brand::REPOSITORY.to_string(), + current: Version::parse("1.0.0").expect("a version"), + target: Some(Target { os: Os::Windows, arch: "x64" }), + prerelease: false, + manifest_url: None, + } + } + + fn feed(version: &str) -> String { + serde_json::json!([{ + "tag_name": format!("v{version}"), + "name": format!("App v{version}"), + "body": "notes", + "published_at": "2026-10-12T00:00:00Z", + "assets": [ + {"name": format!("app-{version}-windows-x64.msi"), "browser_download_url": "https://x/a.msi", "size": 100}, + ], + }]) + .to_string() + } + + fn run(opts: &Options, body: &str) -> Result, UpdateError> { + check(opts, Some(body), None) + } + + #[test] + fn finds_a_newer_release_and_picks_the_file() { + let u = run(&opts(), &feed("1.2.0")).expect("a check").expect("an update"); + assert_eq!((u.current.to_text().as_str(), u.version_text().as_str()), ("1.0.0", "1.2.0")); + assert_eq!(u.asset.name, "app-1.2.0-windows-x64.msi"); + assert_eq!(u.asset.size, 100); + assert_eq!(u.action, "run the 64-bit installer and then start the app again"); + assert_eq!(u.title, "App v1.2.0"); + assert_eq!(u.published.as_deref(), Some("2026-10-12")); + assert_eq!(u.notes, "notes"); + assert_eq!(u.tag, "v1.2.0"); + assert_eq!(u.sha256, None, "this release publishes no sums file"); + } + + #[test] + fn the_same_version_or_an_older_one_is_not_an_update() { + assert!(run(&opts(), &feed("1.0.0")).expect("a check").is_none()); + assert!(run(&opts(), &feed("0.9.9")).expect("a check").is_none()); + // a development build ahead of the newest release stays quiet + let ahead = Options { current: Version::parse("1.3.0").expect("v"), ..opts() }; + assert!(run(&ahead, &feed("1.2.0")).expect("a check").is_none()); + } + + #[test] + fn a_release_without_our_file_is_reported() { + let mac = Options { target: Some(Target { os: Os::Macos, arch: "universal" }), ..opts() }; + let err = run(&mac, &feed("1.2.0")).expect_err("no dmg"); + assert!(matches!(err, UpdateError::NoAssetFor { .. }), "{err}"); + assert!(err.to_string().contains("macos-universal"), "{err}"); + } + + #[test] + fn a_platform_we_do_not_build_for_says_so() { + let none = Options { target: None, ..opts() }; + let err = run(&none, &feed("1.2.0")).expect_err("no platform"); + assert!(matches!(err, UpdateError::Unsupported(_)), "{err}"); + } + + #[test] + fn urls_are_what_github_serves() { + assert_eq!(manifest_url("a/b"), "https://github.com/a/b/releases/latest/download/latest.json"); + assert_eq!(manifest_url("/a/b/"), "https://github.com/a/b/releases/latest/download/latest.json"); + assert_eq!(api_url("a/b"), "https://api.github.com/repos/a/b/releases?per_page=30"); + } + + #[test] + fn the_cache_answers_again_and_claims_one_check() { + let c = Cache::default(); + let o = opts(); + assert!(c.get(&o).is_none()); + c.put(&o, Checked::Current("1.0.0".into())); + assert_eq!(c.get(&o), Some(Checked::Current("1.0.0".into()))); + let other = Options { prerelease: true, ..opts() }; + assert!(c.get(&other).is_none(), "different options: a different question"); + assert!(c.begin(), "the first check takes the slot"); + assert!(!c.begin(), "a second one waits"); + c.end(); + assert!(c.begin()); + } + + #[test] + fn defaults_come_from_the_brand() { + let o = Options::default(); + assert_eq!(o.repo, lcc_brand::REPOSITORY); + assert_eq!(o.current, Version::current()); + assert_eq!(o.target, Target::current()); + assert!(!o.prerelease); + } + + #[test] + fn a_checksums_asset_pins_the_download() { + let body = serde_json::json!([{ + "tag_name": "v1.2.0", + "assets": [ + {"name": "app-1.2.0-windows-x64.msi", "browser_download_url": "https://x/a.msi", "size": 100}, + {"name": "SHA256SUMS.txt", "browser_download_url": "http://127.0.0.1:1/sums", "size": 40}, + ], + }]) + .to_string(); + // the sums file is unreachable here: the update still comes back, without a hash + let u = run(&opts(), &body).expect("a check").expect("an update"); + assert_eq!(u.sha256, None); + assert_eq!(u.asset.kind, crate::target::Kind::Msi); + } +} diff --git a/crates/updater/src/checksum.rs b/crates/updater/src/checksum.rs new file mode 100644 index 0000000000..03ba33bfa2 --- /dev/null +++ b/crates/updater/src/checksum.rs @@ -0,0 +1,69 @@ +//! `SHA256SUMS.txt` from a release: the checksums the pipeline publishes beside every artifact. +//! +//! It is coreutils' format — ` ` per line, `*` instead of the second space +//! for binary mode, `#` comments — and it may be missing or truncated without that breaking +//! anything (the size and the TLS-verified download still check out). + +/// The SHA-256 recorded for `name`, lower-case hex, if the file lists it. +pub fn lookup(text: &str, name: &str) -> Option { + let want = name.trim(); + if want.is_empty() { + return None; + } + for line in text.lines().take(4_000) { + let line = line.trim(); + if line.is_empty() || line.starts_with('#') { + continue; + } + let Some((digest, rest)) = line.split_once(char::is_whitespace) else { continue }; + if !is_sha256(digest) { + continue; + } + let file = rest.trim_start().strip_prefix('*').unwrap_or(rest.trim_start()).trim(); + // the pipeline writes plain file names; a path is matched on its last segment + if file == want || file.rsplit('/').next() == Some(want) || file.rsplit('\\').next() == Some(want) { + return Some(digest.to_ascii_lowercase()); + } + } + None +} + +fn is_sha256(s: &str) -> bool { + s.len() == 64 && s.bytes().all(|b| b.is_ascii_hexdigit()) +} + +#[cfg(test)] +mod tests { + use super::*; + + const APPIMAGE_SHA: &str = "aa11bb22cc33dd44ee55ff6600112233445566778899aabbccddeeff00112233"; + const APPIMAGE_SHA_UPPER: &str = "AA11BB22CC33DD44EE55FF6600112233445566778899AABBCCDDEEFF00112233"; + + fn sums() -> String { + format!( + "# release 1.2.3\n\ + d1e8f2 app-1.2.3-windows-x64.msi\n\ + {APPIMAGE_SHA} *app-1.2.3-linux-x86_64.AppImage\n\ + not-a-hash app-1.2.3-macos-universal.dmg\n" + ) + } + + #[test] + fn finds_a_named_file() { + let text = sums(); + assert_eq!(lookup(&text, "app-1.2.3-windows-x64.msi"), None, "a short digest is not a SHA-256"); + assert_eq!(lookup(&text, "app-1.2.3-linux-x86_64.AppImage").as_deref(), Some(APPIMAGE_SHA)); + assert_eq!(lookup(&text, "app-1.2.3-macos-universal.dmg"), None); + assert_eq!(lookup(&text, "app-9.9.9-windows-x64.msi"), None); + assert_eq!(lookup(&text, ""), None); + assert_eq!(lookup("", "x"), None); + } + + #[test] + fn accepts_paths_and_case() { + let text = format!("{APPIMAGE_SHA_UPPER} dist/app.msi\n"); + assert_eq!(lookup(&text, "app.msi").as_deref(), Some(APPIMAGE_SHA)); + let nested = format!("{APPIMAGE_SHA} ./a/b/app.msi"); + assert_eq!(lookup(&nested, "app.msi").as_deref(), Some(APPIMAGE_SHA)); + } +} diff --git a/crates/updater/src/download.rs b/crates/updater/src/download.rs new file mode 100644 index 0000000000..bcc99532da --- /dev/null +++ b/crates/updater/src/download.rs @@ -0,0 +1,368 @@ +//! Fetching the update file: resumable, capped, and checked before it is given a real name. +//! +//! The transfer itself is [`lcc_net::Client::download`] (pure Rust, TLS-verified, `Range` resume +//! from a `.part` file, size cap, SHA-256 check, delete on mismatch). This module only decides +//! *where* it goes, *how big* it may be and *what* it must hash to, and names the file after the +//! release so two versions never overwrite each other's parts. + +use std::path::{Path, PathBuf}; +use std::sync::Arc; +use std::sync::atomic::AtomicBool; + +use lcc_net::{Client, DownloadOptions}; + +use crate::check::MAX_DOWNLOAD_BYTES; +use crate::check::Update; +use crate::error::UpdateError; + +/// Progress: `(bytes so far, total when known)`. +pub type Progress<'a> = &'a mut dyn FnMut(u64, Option); + +/// What arrived, and where. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Downloaded { + pub path: PathBuf, + pub bytes: u64, + /// Lower-case hex SHA-256 of the file as it was written. + pub sha256: String, + /// The file name, as the release spelled it. + pub name: String, +} + +/// The default staging folder inside a cache root: `/updates`. +pub fn stage_dir(cache_root: &Path) -> PathBuf { + cache_root.join("updates") +} + +/// A client for fetching update files: a long stall timeout (an installer is large) and a body cap +/// that [`lcc_net::Client::download`] does not need but nothing else may exceed either way. +pub fn client() -> Result { + Client::new(lcc_net::ClientConfig { + connect_timeout: std::time::Duration::from_secs(15), + stall_timeout: std::time::Duration::from_secs(60), + max_body: MAX_DOWNLOAD_BYTES, + ..lcc_net::ClientConfig::default() + }) + .map_err(|e| UpdateError::Net(e.to_string())) +} + +/// `.part`, the file a transfer resumes from (the net crate's own convention). +pub fn part_path(dest: &Path) -> PathBuf { + let mut name = dest.file_name().map(|n| n.to_os_string()).unwrap_or_default(); + name.push(".part"); + dest.with_file_name(name) +} + +/// The file name an asset may be saved under: its last path segment, and never `.`/`..`. +/// +/// A feed is remote input: an asset name like `../../.ssh/authorized_keys` must not be able to +/// write outside the staging folder. +pub fn safe_file_name(name: &str) -> Result { + let trimmed = name.trim(); + let base = trimmed.rsplit(['/', '\\']).next().unwrap_or(""); + if base.is_empty() || base == "." || base == ".." || base.contains('\0') || base.chars().any(|c| c.is_control()) { + return Err(UpdateError::Install(format!("the release names its file `{trimmed}`, which is not a usable file name"))); + } + // a conservative length: most file systems stop at 255 bytes + if base.len() > 180 { + return Err(UpdateError::Install("the release's file name is too long to save".into())); + } + Ok(base.to_string()) +} + +/// Download `update`'s file into `dir`, checking it against the feed's size and its SHA-256. +/// +/// A file already there that still matches its SHA-256 is returned as it is (a second click starts +/// no second transfer); a `.part` from an interrupted one is resumed. +pub fn download( + update: &Update, + client: &Client, + dir: &Path, + cancel: Option>, + progress: Option>, +) -> Result { + let name = safe_file_name(&update.asset.name)?; + std::fs::create_dir_all(dir).map_err(|e| UpdateError::Io(format!("could not create {}: {e}", dir.display())))?; + let dest = dir.join(&name); + // where it must not escape to + if dest.parent() != Some(dir) { + return Err(UpdateError::Io(format!("refusing to write outside {}", dir.display()))); + } + let size = (update.asset.size > 0).then_some(update.asset.size); + if let Some(done) = already_verified(&dest, &name, size, update.sha256.as_deref()) { + return Ok(done); + } + let cap = match size { + Some(bytes) => bytes.max(1), + None => MAX_DOWNLOAD_BYTES, + }; + let hash_we_want = update.sha256.clone(); + let opts = DownloadOptions { size, sha256: hash_we_want.clone(), max_size: cap, headers: Vec::new(), cancel, progress }; + let got = client.download(&update.asset.url, &dest, opts).map_err(|e| match e { + lcc_net::NetError::Cancelled => UpdateError::Cancelled, + lcc_net::NetError::Verify(why) => UpdateError::Verify(why), + lcc_net::NetError::TooLarge(bytes) => UpdateError::Verify(format!("the file is larger than the release says ({bytes} bytes)")), + lcc_net::NetError::Io(why) => UpdateError::Io(why), + other => UpdateError::Net(other.to_string()), + })?; + // a resume that needed no transfer still has to hash what was already there; the net crate did + // that, so `got` is the whole file either way + if let Some(size) = size + && got.bytes != size + { + let _ = std::fs::remove_file(&dest); + return Err(UpdateError::Verify(format!("the release says {size} bytes, the file has {}", got.bytes))); + } + Ok(Downloaded { path: dest, bytes: got.bytes, sha256: got.sha256, name }) +} + +/// A file already staged from an earlier download that still checks out, if there is one. +/// +/// The size and the hash are re-read from disk: the folder is on the user's machine, and trusting +/// a file because of its name would be trusting whatever wrote it last. +fn already_verified(dest: &Path, name: &str, size: Option, sha256: Option<&str>) -> Option { + let meta = std::fs::metadata(dest).ok()?; + if !meta.is_file() { + return None; + } + let bytes = meta.len(); + if let Some(want) = size + && bytes != want + { + return None; + } + let sha256 = sha256?; + let got = hash_file(dest).ok()?; + if !got.eq_ignore_ascii_case(sha256) { + // whatever it is, it is not what we are about to install + let _ = std::fs::remove_file(dest); + return None; + } + Some(Downloaded { path: dest.to_path_buf(), bytes, sha256: got, name: name.to_string() }) +} + +/// Lower-case hex SHA-256 of a file, in chunks (an update can be hundreds of megabytes). +fn hash_file(path: &Path) -> Result { + use sha2::{Digest, Sha256}; + use std::io::Read as _; + let mut file = std::fs::File::open(path)?; + let mut hasher = Sha256::new(); + let mut buf = vec![0u8; 256 * 1024]; + loop { + let n = file.read(&mut buf)?; + if n == 0 { + break; + } + hasher.update(buf.get(..n).unwrap_or_default()); + } + Ok(hasher.finalize().iter().map(|b| format!("{b:02x}")).collect()) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::target::{Asset, Kind, Os, Target}; + use crate::version::Version; + + fn update(url: &str, name: &str, size: u64, sha: Option) -> Update { + Update { + current: Version::parse("1.0.0").expect("v"), + version: Version::parse("2.0.0").expect("v"), + title: "App 2.0.0".into(), + tag: "v2.0.0".into(), + asset: Asset { name: name.into(), url: url.into(), size, sha256: sha.clone(), kind: Kind::Msi }, + sha256: sha, + published: None, + notes: String::new(), + action: Target { os: Os::Linux, arch: "x86_64" }.describe(), + } + } + + #[test] + fn names_are_sanitised() { + assert_eq!(safe_file_name("app-1.2.3-windows-x64.msi").as_deref(), Ok("app-1.2.3-windows-x64.msi")); + assert_eq!(safe_file_name(" app.msi ").as_deref(), Ok("app.msi")); + assert_eq!(safe_file_name("dist/app.msi").as_deref(), Ok("app.msi")); + assert_eq!(safe_file_name("..\\..\\.ssh\\authorized_keys").as_deref(), Ok("authorized_keys"), "only the last segment survives"); + for bad in ["", " ", ".", "..", "a/b/..", "a\0b"] { + assert!(safe_file_name(bad).is_err(), "{bad:?} must be refused"); + } + assert!(safe_file_name(&"x".repeat(200)).is_err(), "an absurdly long name is refused"); + } + + #[test] + fn a_part_file_sits_beside_its_target() { + assert_eq!(part_path(Path::new("/tmp/a.msi")), PathBuf::from("/tmp/a.msi.part")); + assert_eq!(part_path(Path::new("C:/tmp/a.msi")).file_name().and_then(|n| n.to_str()), Some("a.msi.part")); + } + + #[test] + fn stage_dir_is_inside_the_cache() { + assert_eq!(stage_dir(Path::new("/cache")), PathBuf::from("/cache/updates")); + } + + /// A local server that answers `n` requests with `body` (and a broken one that hangs up). + fn serve(n: usize, body: Vec) -> String { + use std::io::{BufRead, BufReader, Write}; + let l = std::net::TcpListener::bind("127.0.0.1:0").expect("bind"); + let base = format!("http://{}/f", l.local_addr().expect("addr")); + std::thread::spawn(move || { + for _ in 0..n { + let Ok((mut s, _)) = l.accept() else { return }; + let mut r = BufReader::new(s.try_clone().expect("clone")); + let mut range = String::new(); + loop { + let mut line = String::new(); + if r.read_line(&mut line).unwrap_or(0) == 0 || line.trim().is_empty() { + break; + } + if line.to_ascii_lowercase().starts_with("range:") { + range = line[6..].trim().to_string(); + } + } + let start: usize = range.strip_prefix("bytes=").and_then(|r| r.split('-').next()).and_then(|s| s.parse().ok()).unwrap_or(0); + let slice = body.get(start..).unwrap_or_default(); + if start > 0 { + let _ = s.write_all( + format!( + "HTTP/1.1 206 Partial Content\r\nContent-Length: {}\r\nContent-Range: bytes {start}-{}/{}\r\nConnection: close\r\n\r\n", + slice.len(), + body.len().saturating_sub(1), + body.len() + ) + .as_bytes(), + ); + } else { + let _ = s.write_all(format!("HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", slice.len()).as_bytes()); + } + let _ = s.write_all(slice); + } + }); + base + } + + fn scratch(tag: &str) -> PathBuf { + let d = std::env::temp_dir().join(format!("lcc-updater-{tag}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&d); + std::fs::create_dir_all(&d).expect("scratch"); + d + } + + fn client() -> Client { + Client::new(lcc_net::ClientConfig { stall_timeout: std::time::Duration::from_secs(5), ..Default::default() }).expect("client") + } + + fn sha256_hex(bytes: &[u8]) -> String { + use sha2::Digest as _; + let mut h = sha2::Sha256::new(); + h.update(bytes); + h.finalize().iter().map(|b| format!("{b:02x}")).collect() + } + + #[test] + fn downloads_checks_and_leaves_no_part() { + let dir = scratch("ok"); + let bytes: Vec = (0..50_000u32).map(|i| (i % 251) as u8).collect(); + let url = serve(1, bytes.clone()); + let u = update(&format!("{url}/app.msi"), "app.msi", bytes.len() as u64, Some(sha256_hex(&bytes))); + let mut seen = 0u64; + let got = download(&u, &client(), &dir, None, Some(&mut |done, _| seen = done)).expect("download"); + assert_eq!((got.bytes, std::fs::read(&got.path).expect("read")), (bytes.len() as u64, bytes.clone())); + assert_eq!(got.sha256, sha256_hex(&bytes)); + assert_eq!(seen, bytes.len() as u64, "progress reports the end"); + assert!(!dir.join("app.msi.part").exists()); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn a_wrong_hash_is_thrown_away() { + let dir = scratch("bad"); + let bytes = vec![7u8; 5_000]; + let url = serve(1, bytes.clone()); + let u = update(&format!("{url}/app.msi"), "app.msi", bytes.len() as u64, Some("00".repeat(32))); + let err = download(&u, &client(), &dir, None, None).expect_err("must fail"); + assert!(matches!(err, UpdateError::Verify(_)), "{err}"); + assert_eq!(std::fs::read_dir(&dir).expect("dir").count(), 0, "neither the file nor its part is kept"); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn a_truncated_file_is_not_renamed_into_place() { + let dir = scratch("short"); + let bytes = vec![1u8; 5_000]; + let url = serve(1, bytes.clone()); + // the release says 9 000 bytes; the server sends 5 000 + let u = update(&format!("{url}/app.msi"), "app.msi", 9_000, None); + let err = download(&u, &client(), &dir, None, None).expect_err("must fail"); + assert!(matches!(err, UpdateError::Verify(_)), "{err}"); + assert!(!dir.join("app.msi").exists()); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn an_unreachable_server_is_an_error_not_a_panic() { + let dir = scratch("down"); + let u = update("http://127.0.0.1:1/app.msi", "app.msi", 10, None); + let err = download(&u, &client(), &dir, None, None).expect_err("must fail"); + assert!(matches!(err, UpdateError::Net(_)), "{err}"); + assert_eq!(std::fs::read_dir(&dir).expect("dir").count(), 0); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn a_second_call_reuses_the_verified_file() { + let dir = scratch("again"); + let bytes = vec![3u8; 4_000]; + // one request: the second call finds the verified file already there + let url = serve(1, bytes.clone()); + let u = update(&format!("{url}/app.msi"), "app.msi", bytes.len() as u64, Some(sha256_hex(&bytes))); + let first = download(&u, &client(), &dir, None, None).expect("first"); + // nothing listens now: the verified copy is used as it is + let again = download(&u, &client(), &dir, None, None).expect("second"); + assert_eq!(first, again); + assert_eq!(std::fs::read(&again.path).expect("read"), bytes); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn a_staged_file_that_no_longer_matches_is_fetched_again() { + let dir = scratch("stale"); + let bytes: Vec = (0..9_000u32).map(|i| (i % 97) as u8).collect(); + // what an earlier, different build left under the same name + std::fs::write(dir.join("app.msi"), vec![0u8; bytes.len()]).expect("stale"); + let url = serve(1, bytes.clone()); + let u = update(&format!("{url}/app.msi"), "app.msi", bytes.len() as u64, Some(sha256_hex(&bytes))); + let got = download(&u, &client(), &dir, None, None).expect("re-download"); + assert_eq!(std::fs::read(&got.path).expect("read"), bytes); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn an_interrupted_transfer_resumes() { + let dir = scratch("resume"); + let bytes: Vec = (0..20_000u32).map(|i| (i % 241) as u8).collect(); + let half = bytes.len() / 2; + // what an interrupted transfer left behind + std::fs::write(dir.join("app.msi.part"), &bytes[..half]).expect("part"); + let url = serve(1, bytes.clone()); + let u = update(&format!("{url}/app.msi"), "app.msi", bytes.len() as u64, Some(sha256_hex(&bytes))); + let got = download(&u, &client(), &dir, None, None).expect("resume"); + assert_eq!(got.bytes, bytes.len() as u64); + assert_eq!(std::fs::read(&got.path).expect("read"), bytes); + assert!(!dir.join("app.msi.part").exists()); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn a_hostile_name_stays_in_the_staging_folder() { + let dir = scratch("hostile"); + let bytes = vec![5u8; 100]; + let url = serve(1, bytes.clone()); + let u = update(&format!("{url}/evil"), "../../escaped.msi", bytes.len() as u64, Some(sha256_hex(&bytes))); + let got = download(&u, &client(), &dir, None, None).expect("download"); + assert_eq!(got.path.parent(), Some(dir.as_path())); + assert_eq!(got.name, "escaped.msi"); + assert!(!dir.parent().expect("parent").join("escaped.msi").exists()); + let _ = std::fs::remove_dir_all(&dir); + } +} diff --git a/crates/updater/src/error.rs b/crates/updater/src/error.rs new file mode 100644 index 0000000000..73b5354cc1 --- /dev/null +++ b/crates/updater/src/error.rs @@ -0,0 +1,77 @@ +//! The one error type: everything a check, download or install can fail with, worded for a dialog +//! (no panics, no placeholders). + +/// Why an update check, download or install did not finish. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum UpdateError { + /// The machine's platform has no release artifact (nothing to update with). + Unsupported(String), + /// The release feed could not be read at all. + Net(String), + /// The server answered a status we can't use (`404`, `403` rate-limited…). + Http { code: u16, what: String }, + /// The feed is not the JSON we expect. + Parse(String), + /// The newest release has no file for this platform. + NoAssetFor { version: String, target: String }, + /// The download did not match its expected size or SHA-256. + Verify(String), + /// Writing the downloaded file failed (permissions, disk space). + Io(String), + /// Installing the downloaded file failed. + Install(String), + /// The user cancelled. + Cancelled, +} + +impl std::fmt::Display for UpdateError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + UpdateError::Unsupported(why) => write!(f, "{why}"), + UpdateError::Net(why) => write!(f, "could not reach the release server: {why}"), + UpdateError::Http { code, what } => write!(f, "the release server answered {code} ({what})"), + UpdateError::Parse(why) => write!(f, "the release information could not be read: {why}"), + UpdateError::NoAssetFor { version, target } => { + write!(f, "release {version} has no download for this system ({target}); get it from the releases page instead") + } + UpdateError::Verify(why) => write!(f, "the downloaded update did not check out: {why}"), + UpdateError::Io(why) => write!(f, "{why}"), + UpdateError::Install(why) => write!(f, "the update could not be installed: {why}"), + UpdateError::Cancelled => write!(f, "cancelled"), + } + } +} + +impl std::error::Error for UpdateError {} + +impl From for UpdateError { + fn from(e: lcc_net::NetError) -> Self { + match e { + lcc_net::NetError::Status { code, reason } => UpdateError::Http { code, what: reason }, + other => UpdateError::Net(other.to_string()), + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn messages_are_actionable() { + let e = UpdateError::NoAssetFor { version: "1.2.3".into(), target: "linux-riscv64".into() }; + let text = e.to_string(); + assert!(text.contains("1.2.3") && text.contains("linux-riscv64") && text.contains("releases page"), "{text}"); + assert!(UpdateError::Http { code: 403, what: "rate limited".into() }.to_string().contains("403")); + assert!(UpdateError::Net("dns".into()).to_string().contains("dns")); + assert_eq!(UpdateError::Cancelled.to_string(), "cancelled"); + } + + #[test] + fn a_status_maps_to_http() { + let e: UpdateError = lcc_net::NetError::Status { code: 404, reason: "Not Found".into() }.into(); + assert_eq!(e, UpdateError::Http { code: 404, what: "Not Found".into() }); + let e: UpdateError = lcc_net::NetError::Cancelled.into(); + assert!(matches!(e, UpdateError::Net(_))); + } +} diff --git a/crates/updater/src/install.rs b/crates/updater/src/install.rs new file mode 100644 index 0000000000..8c616eb174 --- /dev/null +++ b/crates/updater/src/install.rs @@ -0,0 +1,423 @@ +//! Installing what was downloaded. +//! +//! Every platform ends the same way: the new build is running, or the user is told in one sentence +//! what to do next. Nothing here panics, and nothing touches the current installation until the +//! replacement file is complete and checked ([`crate::download`]). +//! +//! | Platform | Artifact | What happens | +//! |---|---|---| +//! | Windows | `.msi` | the installer runs (`msiexec`), then the app starts again | +//! | macOS | `.dmg` | mounted, the app copied over the running one, relaunched from a terminal | +//! | Linux | `.AppImage` | the running file is replaced and the new one started | +//! | anywhere else | `.tar.gz` / `.zip` | the folder it is in is shown, to unpack it yourself | +//! +//! The caller quits the app when [`Outcome::exit`] is `true` — the installer or the replacement +//! script needs the running program out of the way — and shows [`Outcome::message`] either way. + +use std::path::{Path, PathBuf}; +use std::process::Command; + +use crate::download::Downloaded; +use crate::error::UpdateError; +use crate::target::Kind; + +/// What the caller has to do once the install has been started. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Restart { + /// Quit now: the installer or replacement script takes over and starts the app again. + QuitAndRelaunch, + /// Keep running: the new build starts when the user starts it. + QuitOnly, + /// Quit when convenient: the download is laid out for a manual install. + Manual, +} + +/// What installing this file will do, in the order it happens. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Plan { + /// One line for the dialog's title area. + pub summary: String, + /// The steps, in order, as short sentences. + pub steps: Vec, + /// Where the file ends up, when that is a place we know. + pub destination: Option, + pub restart: Restart, +} + +/// The result of starting the install. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Outcome { + /// What to tell the user. + pub message: String, + /// Whether the caller must quit for it to finish. + pub exit: bool, +} + +impl Outcome { + /// The outcome for a manual install: the file is there, the user unpacks it. + pub fn manual(file: &Path) -> Outcome { + Outcome { + message: format!("The update was downloaded to {}. Quit the app and unpack it over this installation.", file.display()), + exit: false, + } + } +} + +/// What installing `file` (an asset of `kind`) on this machine would do. +pub fn plan(kind: Kind, file: &Path, version: &str) -> Plan { + match kind { + Kind::Msi => Plan { + summary: format!("Run the {version} installer"), + steps: vec![ + "The app quits so the installer can replace its files.".into(), + "Windows asks for permission when the installer needs it.".into(), + "The app starts again when the installer is done.".into(), + ], + destination: None, + restart: Restart::QuitAndRelaunch, + }, + Kind::Dmg => Plan { + summary: format!("Install {version} from the disk image"), + steps: vec!["The disk image is opened and its app copied over this one.".into(), "The app starts again when the copy is done.".into()], + destination: install_dir(), + restart: Restart::QuitAndRelaunch, + }, + Kind::AppImage => Plan { + summary: format!("Replace this program with {version}"), + steps: vec![ + "The running program is replaced by the new one (the old one is kept beside it as .old).".into(), + "The new version starts as soon as this one quits.".into(), + ], + destination: current_exe(), + restart: Restart::QuitAndRelaunch, + }, + Kind::Archive => Plan { + summary: format!("Download {version} and install it by hand"), + steps: vec![ + format!("The file is saved beside this download ({}) and its folder is shown.", file.display()), + "Quit the app and unpack it over this installation.".into(), + ], + destination: Some(file.to_path_buf()), + restart: Restart::Manual, + }, + Kind::Checksums => Plan { + summary: "Nothing to install: this is the release's checksum list".into(), + steps: vec!["Pick the file for this system instead.".into()], + destination: None, + restart: Restart::Manual, + }, + } +} + +/// Apply `downloaded`: start the installer, replace the AppImage, or lay the file out. See +/// [`Outcome::exit`]. +pub fn install(kind: Kind, downloaded: &Downloaded, version: &str) -> Result { + match kind { + Kind::Msi => install_msi(&downloaded.path), + Kind::Dmg => install_dmg(&downloaded.path), + Kind::AppImage => install_appimage(&downloaded.path), + Kind::Archive => reveal(&downloaded.path).map(|()| Outcome::manual(&downloaded.path)), + Kind::Checksums => Err(UpdateError::Install("that file is the release's checksum list, not an update".into())), + } + .map_err(|e| match e { + UpdateError::Install(_) => e, + other => UpdateError::Install(other.to_string()), + }) + .map(|mut out| { + if out.message.is_empty() { + out.message = format!("Installing {version} has started."); + } + out + }) +} + +/// The `.app` bundle this program runs from, when it is inside one. +fn app_bundle() -> Option { + let exe = current_exe()?; + exe.ancestors().find(|p| p.extension().is_some_and(|e| e.eq_ignore_ascii_case("app"))).map(Path::to_path_buf) +} + +/// Where the app bundle lives (`/Applications` when it is not inside a bundle). +fn install_dir() -> Option { + match app_bundle() { + Some(bundle) => bundle.parent().map(Path::to_path_buf), + None => Some(PathBuf::from("/Applications")), + } +} + +fn current_exe() -> Option { + let exe = std::env::current_exe().ok()?; + Some(std::fs::canonicalize(&exe).unwrap_or(exe)) +} + +/// `'…'` for a POSIX shell: an embedded `'` is closed, escaped and reopened. +#[cfg(unix)] +fn sh_quote(text: &str) -> String { + format!("'{}'", text.replace('\'', "'\\''")) +} + +// ---------- Windows + +#[cfg(windows)] +fn install_msi(msi: &Path) -> Result { + // `/passive` shows the installer's progress bar without asking questions, `/norestart` keeps + // the machine up. The installer needs this process gone to replace the exe, so it is started + // and the caller exits; when it needs elevation Windows asks through `msiexec` itself. + // `Command` quotes the path itself when it holds spaces; quoting it again here would hand + // msiexec literal `\"` characters. + let child = Command::new("msiexec") + .arg("/i") + .arg(msi) + .arg("/passive") + .arg("/norestart") + .spawn() + .map_err(|e| UpdateError::Install(format!("could not start the installer ({}): {e}", msi.display())))?; + Ok(Outcome { message: format!("The installer is running (process {}). The app will start again when it finishes.", child.id()), exit: true }) +} + +#[cfg(not(windows))] +fn install_msi(msi: &Path) -> Result { + Err(UpdateError::Install(format!("{} is a Windows installer; this system runs it another way", msi.display()))) +} + +// ---------- macOS + +#[cfg(target_os = "macos")] +fn install_dmg(dmg: &Path) -> Result { + let target = install_dir().ok_or_else(|| UpdateError::Install("could not tell where this app is installed".into()))?; + let app = app_bundle() + .and_then(|b| b.file_name().map(|n| n.to_string_lossy().to_string())) + .unwrap_or_else(|| format!("{}.app", lcc_brand::DISPLAY_NAME)); + // A script in the user's cache, run in a terminal window so its output (and any error the copy + // hits on the way) is visible instead of lost with this process. + let script = std::env::temp_dir().join(format!("{}-update-{}.sh", lcc_brand::BINARY, std::process::id())); + let body = format!( + "#!/bin/sh\n\ + # written by the app's updater: mount the disk image, copy the app over this one, start it\n\ + set -e\n\ + MOUNT=$(mktemp -d /tmp/{binary}-update.XXXXXX)\n\ + cleanup() {{ hdiutil detach \"$MOUNT\" >/dev/null 2>&1 || true; rmdir \"$MOUNT\" >/dev/null 2>&1 || true; }}\n\ + trap cleanup EXIT\n\ + echo \"Mounting {dmg}…\"\n\ + hdiutil attach {dmg} -nobrowse -quiet -mountpoint \"$MOUNT\"\n\ + SRC=$(find \"$MOUNT\" -maxdepth 1 -name '*.app' -print -quit)\n\ + if [ -z \"$SRC\" ]; then echo \"The disk image holds no app.\" >&2; exit 1; fi\n\ + echo \"Copying $SRC to {target}/{app}…\"\n\ + rm -rf {target}/{app}\n\ + ditto \"$SRC\" {target}/{app}\n\ + echo \"Starting {app}…\"\n\ + open {target}/{app}\n", + binary = lcc_brand::BINARY, + dmg = sh_quote(&dmg.to_string_lossy()), + target = sh_quote(&target.to_string_lossy()), + app = sh_quote(&app), + ); + std::fs::write(&script, body).map_err(|e| UpdateError::Io(format!("could not write {}: {e}", script.display())))?; + // `osascript` opens Terminal on the script: the app quits, the script finishes the job and + // starts the new build. Terminal is asked to run the file, not to type anything. + let script_path = script.to_string_lossy().to_string(); + Command::new("osascript") + .arg("-e") + .arg(format!("tell application \"Terminal\" to do script \"sh {}\"", script_path.replace('\\', "\\\\").replace('"', "\\\""))) + .spawn() + .map_err(|e| UpdateError::Install(format!("could not open a terminal to finish the update: {e}")))?; + Ok(Outcome { + message: format!( + "The disk image is being installed into {}. A terminal window shows the progress; the app starts again when it is done.", + target.display() + ), + exit: true, + }) +} + +#[cfg(not(target_os = "macos"))] +fn install_dmg(dmg: &Path) -> Result { + Err(UpdateError::Install(format!("{} is a macOS disk image; this system runs it another way", dmg.display()))) +} + +// ---------- Linux (and other Unix) + +#[cfg(all(unix, not(target_os = "macos")))] +fn install_appimage(new: &Path) -> Result { + use std::os::unix::fs::PermissionsExt; + + if !new.is_file() { + return Err(UpdateError::Install(format!("{} is not there", new.display()))); + } + // Inside an AppImage `current_exe` is the binary in the read-only squashfs mount; the file + // to replace is the one the runtime names in `$APPIMAGE`. Without it this copy was installed + // another way (a package, a tarball, `cargo install`) and must not be overwritten by an + // AppImage. + let running = appimage_path(std::env::var_os("APPIMAGE")).ok_or_else(|| { + UpdateError::Install(format!( + "this copy of the app is not running from an AppImage; the update was downloaded to {}, install it the way this copy was installed", + new.display() + )) + })?; + // the new file goes beside the old one first, so replacing it is a rename on the same file + // system (atomic, and it cannot fail half way across devices) + let staged = running.with_file_name(format!("{}.new-{}", file_name(&running), std::process::id())); + std::fs::copy(new, &staged).map_err(|e| UpdateError::Install(format!("could not place the new version next to {}: {e}", running.display())))?; + std::fs::set_permissions(&staged, std::fs::Permissions::from_mode(0o755)) + .map_err(|e| UpdateError::Install(format!("could not make {} runnable: {e}", staged.display())))?; + let old = running.with_file_name(format!("{}.old", file_name(&running))); + // A script finishes the swap after this process is gone: a running executable cannot be + // replaced underneath itself, but it can be renamed, and the new one started in its place. + let script = std::env::temp_dir().join(format!("{}-update-{}.sh", lcc_brand::BINARY, std::process::id())); + let body = format!( + "#!/bin/sh\n\ + # written by the app's updater: replace the running AppImage once it has quit, then start it\n\ + for i in $(seq 1 100); do\n\ + \x20 if mv {running} {old} 2>/dev/null; then break; fi\n\ + \x20 sleep 0.1\n\ + done\n\ + if ! mv {staged} {running} 2>/dev/null; then\n\ + \x20 echo 'The new version could not be put in place; the old one was kept.' >&2\n\ + \x20 mv {old} {running} 2>/dev/null || true\n\ + \x20 exit 1\n\ + fi\n\ + setsid {running} \"$@\" >/dev/null 2>&1 < /dev/null &\n", + running = sh_quote(&running.to_string_lossy()), + old = sh_quote(&old.to_string_lossy()), + staged = sh_quote(&staged.to_string_lossy()), + ); + std::fs::write(&script, body).map_err(|e| UpdateError::Io(format!("could not write {}: {e}", script.display())))?; + Command::new("/bin/sh") + .arg(&script) + .stdin(std::process::Stdio::null()) + .stdout(std::process::Stdio::null()) + .stderr(std::process::Stdio::null()) + .spawn() + .map_err(|e| UpdateError::Install(format!("could not start the replacement: {e}")))?; + Ok(Outcome { + message: format!( + "The new version replaces {} and starts as soon as the app quits. The previous file is kept as {}.", + running.display(), + old.display() + ), + exit: true, + }) +} + +#[cfg(not(all(unix, not(target_os = "macos"))))] +fn install_appimage(new: &Path) -> Result { + Err(UpdateError::Install(format!("{} is an AppImage; this system installs it another way", new.display()))) +} + +/// The AppImage file to replace, from the runtime's `$APPIMAGE` (an existing file, canonical). +#[cfg(all(unix, not(target_os = "macos")))] +fn appimage_path(var: Option) -> Option { + let path = PathBuf::from(var?); + if !path.is_file() { + return None; + } + Some(std::fs::canonicalize(&path).unwrap_or(path)) +} + +#[cfg(all(unix, not(target_os = "macos")))] +fn file_name(path: &Path) -> String { + path.file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_else(|| lcc_brand::BINARY.to_string()) +} + +// ---------- anything else: show the file + +/// Show `file` in the platform's file manager. +fn reveal(file: &Path) -> Result<(), UpdateError> { + if !file.is_file() { + return Err(UpdateError::Install(format!("{} is not there any more", file.display()))); + } + let dir = file.parent().unwrap_or(file); + let mut cmd = if cfg!(windows) { + let mut c = Command::new("explorer"); + c.arg(format!("/select,{}", file.display())); + c + } else if cfg!(target_os = "macos") { + let mut c = Command::new("open"); + c.arg("-R").arg(file); + c + } else { + let mut c = Command::new("xdg-open"); + c.arg(dir); + c + }; + cmd.spawn().map(|_| ()).map_err(|e| UpdateError::Install(format!("could not show {}: {e}", dir.display()))) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn downloaded(name: &str) -> Downloaded { + Downloaded { path: PathBuf::from("/tmp").join(name), bytes: 1, sha256: String::new(), name: name.into() } + } + + #[test] + fn quoting_keeps_a_path_one_argument() { + #[cfg(unix)] + { + assert_eq!(sh_quote("/tmp/a b"), "'/tmp/a b'"); + assert_eq!(sh_quote("/tmp/it's"), "'/tmp/it'\\''s'"); + } + } + + #[test] + fn plans_say_what_happens() { + let p = plan(Kind::Msi, Path::new("/tmp/a.msi"), "1.2.3"); + assert!(p.summary.contains("1.2.3") && p.summary.contains("installer")); + assert!(!p.steps.is_empty()); + assert_eq!(p.restart, Restart::QuitAndRelaunch); + let a = plan(Kind::Archive, Path::new("/tmp/a.zip"), "1.2.3"); + assert_eq!(a.restart, Restart::Manual); + assert!(a.destination.is_some()); + let c = plan(Kind::Checksums, Path::new("/tmp/SHA256SUMS.txt"), "1.2.3"); + assert!(c.summary.contains("Nothing to install")); + } + + #[test] + fn a_checksum_list_is_never_installed() { + let err = install(Kind::Checksums, &downloaded("SHA256SUMS.txt"), "1.2.3").expect_err("refused"); + assert!(matches!(err, UpdateError::Install(_)), "{err}"); + assert!(err.to_string().contains("checksum")); + } + + #[test] + fn a_windows_installer_is_refused_on_other_systems() { + if cfg!(windows) { + return; + } + let err = install(Kind::Msi, &downloaded("a.msi"), "1.2.3").expect_err("refused"); + assert!(err.to_string().contains("Windows installer"), "{err}"); + } + + #[test] + fn a_missing_archive_is_an_error_not_a_panic() { + let err = install(Kind::Archive, &downloaded("nowhere/a.zip"), "1.2.3").expect_err("refused"); + assert!(matches!(err, UpdateError::Install(_)), "{err}"); + } + + #[test] + fn an_appimage_that_is_not_there_is_refused() { + if cfg!(all(unix, not(target_os = "macos"))) { + let err = install(Kind::AppImage, &downloaded("nowhere.AppImage"), "1.2.3").expect_err("refused"); + assert!(err.to_string().contains("not there"), "{err}"); + } + } + + #[cfg(all(unix, not(target_os = "macos")))] + #[test] + fn only_a_real_appimage_file_is_replaced() { + assert_eq!(appimage_path(None), None, "not started from an AppImage"); + assert_eq!(appimage_path(Some("/nowhere/app.AppImage".into())), None); + let exe = current_exe().expect("test exe"); + assert!(appimage_path(Some(exe.clone().into_os_string())).is_some()); + } + + #[test] + fn the_exe_is_known() { + // the test binary is a real running executable; `current_exe` must find it + assert!(current_exe().is_some()); + if cfg!(target_os = "macos") { + assert_eq!(app_bundle(), None, "a cargo test binary is not inside an .app"); + } + } +} diff --git a/crates/updater/src/lib.rs b/crates/updater/src/lib.rs new file mode 100644 index 0000000000..616947b643 --- /dev/null +++ b/crates/updater/src/lib.rs @@ -0,0 +1,53 @@ +//! The auto updater: find a newer release of the app on GitHub, download the file for this +//! machine, and stage installing it — the shape Tauri's updater has, with no extra service behind +//! it. +//! +//! The pieces, in the order a session uses them: +//! +//! 1. [`check`] reads the release feed — the static `latest.json` the release pipeline publishes, +//! GitHub's Releases API, or a feed URL the environment points at ([`Options::manifest_url`], +//! `_UPDATE_URL`) — compares the newest release's version with this build ([`version`]), +//! and picks the asset that belongs to this platform ([`target`]). +//! 2. [`download`] fetches that asset into the cache folder, resuming an interrupted transfer, +//! capped, and checked against the size the feed states and the release's `SHA256SUMS.txt` +//! ([`checksum`]) before it is renamed into place. A file that fails its check is deleted. +//! 3. [`install`] says what installing will do ([`install::Plan`]) and, when asked, does it: the +//! Windows installer runs, a macOS disk image is mounted and its app copied over the running +//! one, an AppImage replaces itself, and anything else is laid out where the user can unpack +//! it. Every path ends with the app running again, or with a sentence saying what to do. +//! +//! Never a panic: no network, a rate-limited API, a release without a file for this machine, a +//! truncated download, a full disk, an installer that refuses — all are [`UpdateError`] values a +//! dialog can show, and every one of them leaves the current installation untouched. +//! +//! Native only: on wasm32 the crate is empty (the web build updates by reloading the page). +//! +//! Sources: own design, from the documented GitHub Releases API and the Web Linking/CDN layout of +//! release assets; version precedence follows Semantic Versioning 2.0.0. + +#![cfg(not(target_arch = "wasm32"))] +#![forbid(unsafe_code)] +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] + +pub mod checksum; +mod error; +mod release; +mod version; + +mod check; +mod download; +mod install; +mod target; + +pub use check::{Cache, Checked, MAX_DOWNLOAD_BYTES, Options, REUSE_AFTER, Update, api_url, check, from_release, manifest_url, override_url}; +pub use download::{Downloaded, client, download, part_path, stage_dir}; +pub use error::UpdateError; +pub use install::{Plan, Restart, install, plan}; +pub use release::{Release, newest, version_of}; +pub use target::{Asset, Kind, Os, Target}; +pub use version::Version; + +/// The `User-Agent` GitHub's API requires: the brand's binary name and version. +pub fn user_agent() -> String { + lcc_net::user_agent() +} diff --git a/crates/updater/src/release.rs b/crates/updater/src/release.rs new file mode 100644 index 0000000000..3cd862a471 --- /dev/null +++ b/crates/updater/src/release.rs @@ -0,0 +1,244 @@ +//! The release feed: GitHub's Releases API and the static `latest.json` the pipeline publishes. +//! +//! Both are read into the same [`Release`], so the update check does not care which one answered. +//! The API path needs no authentication for a public repository (GitHub rate-limits it per IP, +//! which the caller sees as an [`UpdateError::Http`] with `403`); `latest.json` is a plain file on +//! the release itself and works when the API is rate-limited. + +use serde_json::Value; + +use crate::error::UpdateError; +use crate::target::{Asset, Kind, Target}; +use crate::version::Version; + +/// One release, as much of it as an update needs. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Release { + pub version: Version, + /// The git tag (`v1.2.3`). + pub tag: String, + /// The release's title. + pub title: String, + /// The release notes (Markdown). + pub notes: String, + /// `YYYY-MM-DD` from the feed, when it says. + pub published: Option, + /// Whether the feed marks it a prerelease. + pub prerelease: bool, + /// Every asset we can classify. + pub assets: Vec, +} + +impl Release { + /// Read one release out of a feed entry (GitHub API object or one `releases` array element of + /// `latest.json`). `None` when it is not a release of ours: a draft, or a tag that does not + /// name ` `. + pub fn parse(v: &Value, allow_prerelease: bool) -> Option { + if v.get("draft").and_then(Value::as_bool) == Some(true) { + return None; + } + let tag = v.get("tag_name").or_else(|| v.get("tag")).and_then(Value::as_str).unwrap_or("").trim(); + let version = version_of(tag)?; + let prerelease = v.get("prerelease").and_then(Value::as_bool).unwrap_or(false) || !version.is_release(); + if prerelease && !allow_prerelease { + return None; + } + let notes = v + .get("body") + .or_else(|| v.get("notes")) + .and_then(Value::as_str) + .unwrap_or("") + // a release body is Markdown a maintainer wrote; it is shown, never executed + .chars() + .take(200_000) + .collect::(); + let assets = v.get("assets").and_then(Value::as_array).map(|list| list.iter().filter_map(asset_of).collect()).unwrap_or_default(); + Some(Release { + version, + tag: tag.to_string(), + title: v.get("name").and_then(Value::as_str).unwrap_or(tag).trim().to_string(), + notes, + published: v.get("published_at").or_else(|| v.get("date")).and_then(Value::as_str).map(|s| s.chars().take(10).collect()), + prerelease, + assets, + }) + } + + /// The file to install on `target`: an installer first, then a plain archive; `None` when the + /// release has nothing this platform can use. + pub fn best_asset(&self, target: &Target) -> Option<&Asset> { + self.assets.iter().filter(|a| a.kind != Kind::Checksums && target.matches_name(&a.name)).min_by_key(|a| (a.kind.rank(), a.size)) + } + + /// The release's checksum list, when it publishes one. + pub fn checksum_asset(&self) -> Option<&Asset> { + self.assets.iter().find(|a| a.kind == Kind::Checksums) + } +} + +/// The version a tag names: `v1.2.3` and `1.2.3` both count, anything else (`nightly`) is not a +/// release of ours. +pub fn version_of(tag: &str) -> Option { + Version::parse(tag).ok() +} + +fn asset_of(v: &Value) -> Option { + let name = v.get("name").and_then(Value::as_str)?.trim(); + let url = v.get("browser_download_url").or_else(|| v.get("url")).and_then(Value::as_str)?.trim(); + if url.is_empty() { + return None; + } + let size = v.get("size").and_then(Value::as_u64).unwrap_or(0); + // the API leaves `digest` null for older uploads; `sha256:` when GitHub computed it + let sha256 = v + .get("sha256") + .and_then(Value::as_str) + .or_else(|| v.get("digest").and_then(Value::as_str).and_then(|d| d.strip_prefix("sha256:"))) + .map(str::trim) + .filter(|d| d.len() == 64 && d.bytes().all(|b| b.is_ascii_hexdigit())) + .map(str::to_ascii_lowercase); + Asset::new(name, url, size, sha256) +} + +/// The newest release in a feed: GitHub's `GET /repos/{owner}/{repo}/releases` array, or the +/// `latest.json` object (`{"releases": [...]}` or one release on its own). +pub fn newest(body: &str, allow_prerelease: bool) -> Result { + let json: Value = serde_json::from_str(body).map_err(|e| UpdateError::Parse(e.to_string()))?; + let list: Vec<&Value> = match &json { + Value::Array(items) => items.iter().collect(), + Value::Object(_) => match json.get("releases").and_then(Value::as_array) { + Some(items) => items.iter().collect(), + None => vec![&json], + }, + _ => return Err(UpdateError::Parse("not a release list".into())), + }; + list.iter() + .filter_map(|v| Release::parse(v, allow_prerelease)) + .max_by(|a, b| a.version.cmp(&b.version)) + .ok_or_else(|| UpdateError::Parse("the release list holds no release of this app".into())) + // (the newest by version, not by feed order: the API lists newest first, `latest.json` need not) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn api_release(tag: &str, prerelease: bool, assets: &[(&str, &str, u64)]) -> Value { + serde_json::json!({ + "tag_name": tag, + "name": format!("App {tag}"), + "body": "### Fixed\n- a thing", + "published_at": "2026-10-12T09:31:00Z", + "prerelease": prerelease, + "draft": false, + "assets": assets.iter().map(|(n, u, s)| serde_json::json!({"name": n, "browser_download_url": u, "size": s})).collect::>(), + }) + } + + fn feed() -> String { + serde_json::json!([ + api_release("v0.6.9", false, &[("app-0.6.9-windows-x64.msi", "https://x/6", 10)]), + api_release( + "v0.7.1", + false, + &[ + ("app-0.7.1-windows-x64.msi", "https://x/71", 40), + ("app-0.7.1-windows-x64-portable.zip", "https://x/71z", 30), + ("SHA256SUMS.txt", "https://x/71s", 2), + ("app-0.7.1-linux-x86_64.AppImage", "https://x/71l", 50), + ] + ), + api_release("v0.7.0-rc.2", true, &[("app-0.7.0-rc.2-windows-x64.msi", "https://x/70", 35)]), + api_release("nightly-2026-10-12", false, &[("app-nightly.msi", "https://x/n", 1)]), + ]) + .to_string() + } + + #[test] + fn picks_the_newest_published_release() { + let r = newest(&feed(), false).expect("a release"); + assert_eq!(r.version.to_text(), "0.7.1"); + assert_eq!(r.tag, "v0.7.1"); + assert_eq!(r.title, "App v0.7.1"); + assert_eq!(r.published.as_deref(), Some("2026-10-12")); + assert!(r.notes.contains("a thing")); + assert!(!r.prerelease); + } + + #[test] + fn prereleases_are_off_unless_asked_for() { + assert_eq!(newest(&feed(), false).expect("release").version.to_text(), "0.7.1"); + let with_pre = newest(&feed(), true).expect("release"); + assert_eq!(with_pre.version.to_text(), "0.7.1", "a release still outranks its prereleases"); + let only_pre = serde_json::json!([api_release("v0.8.0-rc.1", true, &[("app.msi", "https://x/a", 1)])]).to_string(); + assert!(newest(&only_pre, false).is_err()); + assert_eq!(newest(&only_pre, true).expect("rc").version.to_text(), "0.8.0-rc.1"); + } + + #[test] + fn a_tag_that_is_not_a_version_is_not_ours() { + let v = serde_json::json!([api_release("docs-2026", false, &[("app.msi", "https://x/a", 1)])]).to_string(); + assert!(newest(&v, false).is_err(), "an unversioned tag is not a release"); + let draft = serde_json::json!([{"tag_name": "v9.9.9", "draft": true, "assets": []}]).to_string(); + assert!(newest(&draft, false).is_err(), "a draft is not published yet"); + } + + #[test] + fn choices_the_installer_over_the_archive() { + let r = newest(&feed(), false).expect("a release"); + let win = Target { os: crate::target::Os::Windows, arch: "x64" }; + let picked = r.best_asset(&win).expect("an msi"); + assert_eq!((picked.name.as_str(), picked.kind), ("app-0.7.1-windows-x64.msi", Kind::Msi)); + assert_eq!(r.checksum_asset().map(|a| a.name.as_str()), Some("SHA256SUMS.txt")); + let lin = Target { os: crate::target::Os::Linux, arch: "x86_64" }; + assert_eq!(r.best_asset(&lin).map(|a| a.name.as_str()), Some("app-0.7.1-linux-x86_64.AppImage")); + let arm = Target { os: crate::target::Os::Linux, arch: "aarch64" }; + assert!(r.best_asset(&arm).is_none(), "no aarch64 file in this release"); + } + + #[test] + fn reads_the_static_manifest() { + let sha = "ab".repeat(32); + let manifest = serde_json::json!({ + "version": "1.0.0", + "notes": "the notes", + "pub_date": "2026-10-12T00:00:00Z", + "releases": [ + {"tag": "v1.0.0", "name": "App 1.0.0", "notes": "the notes", "date": "2026-10-12", + "assets": [{"name": "app-1.0.0-windows-x64.msi", "url": "https://x/1", "size": 7, "sha256": sha}]} + ] + }) + .to_string(); + let r = newest(&manifest, false).expect("a release"); + assert_eq!(r.version.to_text(), "1.0.0"); + assert_eq!(r.notes, "the notes"); + let a = &r.assets[0]; + assert_eq!(a.size, 7); + assert_eq!(a.sha256.as_deref().map(str::len), Some(64)); + assert_eq!(a.kind, Kind::Msi); + } + + #[test] + fn a_single_release_object_works_too() { + let one = serde_json::json!({"tag_name": "v2.0.0", "assets": [{"name": "app-2.0.0-macos-universal.dmg", "browser_download_url": "https://x/d", "size": 3}]}).to_string(); + assert_eq!(newest(&one, false).expect("a release").version.to_text(), "2.0.0"); + } + + #[test] + fn broken_feeds_are_errors_not_panics() { + assert!(matches!(newest("not json", false), Err(UpdateError::Parse(_)))); + assert!(matches!(newest("42", false), Err(UpdateError::Parse(_)))); + assert!(matches!(newest("[]", false), Err(UpdateError::Parse(_)))); + assert!(Version::parse("v1.2.3").is_ok()); + assert!(version_of("v1.2.3-rc.1").is_some()); + assert!(version_of("v1.2").is_none()); + } + + #[test] + fn assets_without_a_url_are_skipped() { + let v = serde_json::json!([{"tag_name": "v1.0.1", "assets": [{"name": "app-1.0.1-windows-x64.msi", "size": 1}]}]).to_string(); + let r = newest(&v, false).expect("a release"); + assert!(r.assets.is_empty()); + assert!(r.best_asset(&Target { os: crate::target::Os::Windows, arch: "x64" }).is_none()); + } +} diff --git a/crates/updater/src/target.rs b/crates/updater/src/target.rs new file mode 100644 index 0000000000..831f6135df --- /dev/null +++ b/crates/updater/src/target.rs @@ -0,0 +1,251 @@ +//! Which release artifact belongs to this machine. +//! +//! The release pipeline names every artifact `---[-portable]` +//! (see `docs/releasing.md` and `packaging/`). This module turns the running platform into that +//! shape and classifies the assets a release offers, so the update check can pick the one file +//! that applies — and say so in words first ([`Target::describe`]). + +/// The platform a release is for. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Os { + Windows, + Macos, + Linux, + Freebsd, +} + +impl Os { + /// The slug the pipeline puts in artifact names (`windows`, `macos`, `linux`, `freebsd`). + pub fn slug(self) -> &'static str { + match self { + Os::Windows => "windows", + Os::Macos => "macos", + Os::Linux => "linux", + Os::Freebsd => "freebsd", + } + } +} + +/// What a release asset is, and therefore what installing it means. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Kind { + /// A Windows `.msi`: run it and let the installer replace this installation. + Msi, + /// A macOS `.dmg`: mount it, copy the app beside the running one, relaunch. + Dmg, + /// A Linux `.AppImage`: replace the running file and start the new one. + AppImage, + /// A tarball or zip (`portable`): unpack it yourself over the current installation. + Archive, + /// The release's `SHA256SUMS.txt`: integrity, not an install. + Checksums, +} + +impl Kind { + /// How much we want this artifact, lower first. Only one of each is ever offered per platform. + pub fn rank(self) -> u8 { + match self { + Kind::Msi | Kind::Dmg | Kind::AppImage => 0, + Kind::Archive => 1, + Kind::Checksums => 9, + } + } + + /// Classify `name` (`--windows-x64.msi`) by its extension and shape. + pub fn of(name: &str) -> Option { + let lower = name.to_ascii_lowercase(); + if lower.ends_with("sha256sums.txt") || lower.ends_with("sha256sums") { + return Some(Kind::Checksums); + } + // `.AppImage.zsync` is delta metadata for AppImageUpdate: not an install by itself + if lower.ends_with(".zsync") { + return None; + } + if lower.ends_with(".msi") { + return Some(Kind::Msi); + } + if lower.ends_with(".dmg") { + return Some(Kind::Dmg); + } + if lower.ends_with(".appimage") { + return Some(Kind::AppImage); + } + if lower.ends_with(".tar.gz") || lower.ends_with(".tgz") || lower.ends_with(".zip") || lower.ends_with(".flatpak") { + return Some(Kind::Archive); + } + None + } + + /// One word for a dialog: how this file is installed. + pub fn installs_by(self) -> &'static str { + match self { + Kind::Msi => "runs the installer", + Kind::Dmg => "copies the app out of the disk image", + Kind::AppImage => "replaces the running program", + Kind::Archive => "unpacks over the current installation", + Kind::Checksums => "lists the checksums", + } + } +} + +/// One asset of a release, as the feed describes it. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Asset { + pub name: String, + pub url: String, + /// Bytes, when the feed says (0 = unknown). + pub size: u64, + /// Lower-case hex SHA-256, when the feed pins one. + pub sha256: Option, + pub kind: Kind, +} + +impl Asset { + /// Build an asset from a feed entry, classifying its name (`None`: not an artifact of ours). + pub fn new(name: impl Into, url: impl Into, size: u64, sha256: Option) -> Option { + let name = name.into(); + let kind = Kind::of(&name)?; + Some(Asset { name, url: url.into(), size, sha256, kind }) + } +} + +/// The platform this build runs on, and which artifacts it can take. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Target { + pub os: Os, + /// `x64`, `x86`, `arm64`, `x86_64`, `aarch64`, `riscv64`. + pub arch: &'static str, +} + +impl Target { + /// The running platform, or `None` on a platform the release pipeline does not build for (the + /// web build has no updater at all). + pub fn current() -> Option { + Target::of(std::env::consts::OS, std::env::consts::ARCH) + } + + /// [`Target::current`] from a pair of `std::env::consts` strings, so the mapping can be tested + /// for every platform we ship. + pub fn of(os: &str, arch: &str) -> Option { + let (os, arch) = match (os, arch) { + ("windows", "x86_64") => (Os::Windows, "x64"), + ("windows", "x86") => (Os::Windows, "x86"), + ("windows", "aarch64") => (Os::Windows, "arm64"), + ("macos", "aarch64") | ("macos", "x86_64") => (Os::Macos, "universal"), + ("linux", "x86_64") => (Os::Linux, "x86_64"), + ("linux", "aarch64") => (Os::Linux, "aarch64"), + ("linux", "riscv64") => (Os::Linux, "riscv64"), + ("freebsd", "x86_64") => (Os::Freebsd, "x86_64"), + _ => return None, + }; + Some(Target { os, arch }) + } + + /// Whether `name` names an artifact for this platform: it carries the OS and architecture slug. + /// The portable Windows zip is deliberately not matched (installing it is a manual unpack). + pub fn matches_name(&self, name: &str) -> bool { + let lower = name.to_ascii_lowercase(); + if lower.contains("portable") { + return false; + } + if !lower.contains(&format!("-{}-", self.os.slug())) { + return false; + } + match self.os { + // the macOS build is one universal app; either arch slug is the same file + Os::Macos => lower.contains("-macos-universal") || lower.contains("-macos-x86_64") || lower.contains("-macos-aarch64"), + _ => lower.contains(&format!("-{}-{}", self.os.slug(), self.arch)), + } + } + + /// What the update will do, in one line, before anything is downloaded. + pub fn describe(&self) -> String { + match self.os { + Os::Windows => format!("run the {} installer and then start the app again", self.words_for_arch()), + Os::Macos => "copy the app out of the disk image over this installation and start it again".into(), + Os::Linux if self.arch == "x86_64" || self.arch == "aarch64" => "replace this program with the new one and start it again".into(), + _ => "download it and open the folder it is in, so you can install it".into(), + } + } + + /// How a sentence names this machine's architecture (`64-bit`, `ARM64`, `x86_64`). + fn words_for_arch(&self) -> &'static str { + match self.arch { + "x64" => "64-bit", + "x86" => "32-bit", + "arm64" => "ARM64", + "universal" => "universal", + other => other, + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn classifies_artifacts() { + assert_eq!(Kind::of("app-1.2.3-windows-x64.msi"), Some(Kind::Msi)); + assert_eq!(Kind::of("app-1.2.3-windows-x64-portable.zip"), Some(Kind::Archive)); + assert_eq!(Kind::of("app-1.2.3-macos-universal.dmg"), Some(Kind::Dmg)); + assert_eq!(Kind::of("app-1.2.3-linux-x86_64.AppImage"), Some(Kind::AppImage)); + assert_eq!(Kind::of("app-1.2.3-linux-x86_64.tar.gz"), Some(Kind::Archive)); + assert_eq!(Kind::of("app-1.2.3-freebsd-x86_64.tar.gz"), Some(Kind::Archive)); + assert_eq!(Kind::of("app-1.2.3-linux-x86_64.flatpak"), Some(Kind::Archive)); + assert_eq!(Kind::of("SHA256SUMS.txt"), Some(Kind::Checksums)); + assert_eq!(Kind::of("app-1.2.3-linux-x86_64.AppImage.zsync"), None); + assert_eq!(Kind::of("app-1.2.3-web.zip"), Some(Kind::Archive)); + assert_eq!(Kind::of("notes.md"), None); + assert_eq!(Kind::of("app.exe"), None); + } + + #[test] + fn maps_the_shipped_platforms() { + assert_eq!(Target::of("windows", "x86_64"), Some(Target { os: Os::Windows, arch: "x64" })); + assert_eq!(Target::of("windows", "x86"), Some(Target { os: Os::Windows, arch: "x86" })); + assert_eq!(Target::of("windows", "aarch64"), Some(Target { os: Os::Windows, arch: "arm64" })); + assert_eq!(Target::of("macos", "aarch64"), Some(Target { os: Os::Macos, arch: "universal" })); + assert_eq!(Target::of("macos", "x86_64"), Some(Target { os: Os::Macos, arch: "universal" })); + assert_eq!(Target::of("linux", "riscv64"), Some(Target { os: Os::Linux, arch: "riscv64" })); + assert_eq!(Target::of("freebsd", "x86_64"), Some(Target { os: Os::Freebsd, arch: "x86_64" })); + assert_eq!(Target::of("android", "aarch64"), None); + assert_eq!(Target::of("windows", "powerpc"), None); + } + + #[test] + fn picks_only_this_platforms_files() { + let win = Target { os: Os::Windows, arch: "x64" }; + assert!(win.matches_name("app-1.2.3-windows-x64.msi")); + assert!(!win.matches_name("app-1.2.3-windows-x64-portable.zip"), "the portable zip is a manual install"); + assert!(!win.matches_name("app-1.2.3-windows-arm64.msi")); + assert!(!win.matches_name("app-1.2.3-linux-x86_64.AppImage")); + // a Windows version that only ever mentions x64 in prose still matches: the name is ours + assert!(!win.matches_name("app-1.2.3-linux-x86_64.tar.gz")); + let mac = Target { os: Os::Macos, arch: "universal" }; + assert!(mac.matches_name("app-1.2.3-macos-universal.dmg")); + assert!(mac.matches_name("app-1.2.3-macos-aarch64.dmg"), "a per-arch dmg is still the macOS app"); + assert!(!mac.matches_name("app-1.2.3-windows-x64.msi")); + let lin = Target { os: Os::Linux, arch: "aarch64" }; + assert!(lin.matches_name("app-1.2.3-linux-aarch64.AppImage")); + assert!(!lin.matches_name("app-1.2.3-linux-x86_64.AppImage")); + } + + #[test] + fn describes_what_will_happen() { + assert!(Target { os: Os::Linux, arch: "x86_64" }.describe().contains("replace this program")); + assert!(Target { os: Os::Windows, arch: "x64" }.describe().contains("installer")); + assert!(Target { os: Os::Linux, arch: "riscv64" }.describe().contains("open the folder")); + } + + #[test] + fn asset_ranks_installers_above_archives() { + let msi = Asset::new("a-windows-x64.msi", "https://x/1", 10, None).expect("msi"); + let zip = Asset::new("a-windows-x64-portable.zip", "https://x/2", 10, None).expect("zip"); + let sums = Asset::new("SHA256SUMS.txt", "https://x/3", 10, None).expect("sums"); + assert!(msi.kind.rank() < zip.kind.rank()); + assert!(zip.kind.rank() < sums.kind.rank()); + assert_eq!(Asset::new("app.exe", "https://x/4", 1, None), None); + assert!(msi.kind.installs_by().contains("installer")); + } +} diff --git a/crates/updater/src/version.rs b/crates/updater/src/version.rs new file mode 100644 index 0000000000..4c79a14a2f --- /dev/null +++ b/crates/updater/src/version.rs @@ -0,0 +1,219 @@ +//! Version numbers as release tags spell them (`v1.2.3`, `1.2.3-rc.1`, `1.2.3+build.5`), and the +//! comparison that decides whether a release is newer than the running build. +//! +//! Semantic Versioning 2.0.0 precedence: numeric identifiers compare numerically, a prerelease is +//! lower than the release it leads to, and build metadata is ignored. A tag that is not a version +//! is not a candidate (see [`crate::release::Release::version_of`]). + +/// A parsed version. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Version { + major: u64, + minor: u64, + patch: u64, + /// Dot-separated prerelease identifiers (`rc.1` → `["rc", "1"]`); empty for a release. + pre: Vec, + /// Dot-separated build metadata (`+build.5`); ignored by the ordering. + build: Vec, +} + +impl Version { + /// Parse `1.2.3`, `1.2.3-rc.1`, `1.2.3+build`, with an optional leading `v`/`V`. + /// + /// `major.minor.patch` is required: a tag whose shape we do not understand is not guessed at, + /// it is refused (`"1.2"`, `"nightly"`, `"1.2.3.4"`). + pub fn parse(text: &str) -> Result { + let s = text.trim(); + let s = s.strip_prefix(['v', 'V']).unwrap_or(s); + if s.is_empty() || s.len() > 128 { + return Err(format!("`{text}` is not a version")); + } + let (rest, build) = match s.split_once('+') { + Some((head, meta)) => (head, ids(meta)?), + None => (s, Vec::new()), + }; + let (core, pre) = match rest.split_once('-') { + Some((head, tail)) => (head, ids(tail)?), + None => (rest, Vec::new()), + }; + let mut parts = core.split('.'); + let mut next = |what: &str| -> Result { + let part = parts.next().ok_or_else(|| format!("`{text}` has no {what} number"))?; + // leading zeros and huge numbers are not versions we would ever publish + if part.is_empty() || part.len() > 18 || !part.bytes().all(|b| b.is_ascii_digit()) { + return Err(format!("`{text}`: `{part}` is not a {what} number")); + } + if part.len() > 1 && part.starts_with('0') { + return Err(format!("`{text}`: `{part}` has a leading zero")); + } + part.parse::().map_err(|_| format!("`{text}`: `{part}` is too large")) + }; + let major = next("major")?; + let minor = next("minor")?; + let patch = next("patch")?; + if parts.next().is_some() { + return Err(format!("`{text}` has more than three numbers")); + } + Ok(Version { major, minor, patch, pre, build }) + } + + /// The running build's version, from the crate that was compiled. + pub fn current() -> Version { + Version::parse(env!("CARGO_PKG_VERSION")).unwrap_or(Version { major: 0, minor: 0, patch: 0, pre: Vec::new(), build: Vec::new() }) + } + + /// `1.2.3`, or `1.2.3-rc.1` (build metadata is not shown: it never orders anything). + pub fn to_text(&self) -> String { + let mut out = format!("{}.{}.{}", self.major, self.minor, self.patch); + if !self.pre.is_empty() { + out.push('-'); + out.push_str(&self.pre.join(".")); + } + out + } + + /// A release (`1.2.3`), not a prerelease (`1.2.3-rc.1`). + pub fn is_release(&self) -> bool { + self.pre.is_empty() + } + + /// The prerelease identifiers (`["rc", "1"]`), empty for a release. + pub fn prerelease(&self) -> &[String] { + &self.pre + } +} + +fn ids(text: &str) -> Result, String> { + if text.is_empty() { + return Err("an empty prerelease or build part".into()); + } + let mut out = Vec::new(); + for part in text.split('.') { + if part.is_empty() || part.len() > 64 || !part.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-') { + return Err(format!("`{part}` is not a version identifier")); + } + out.push(part.to_string()); + } + Ok(out) +} + +impl std::fmt::Display for Version { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(&self.to_text()) + } +} + +impl PartialOrd for Version { + fn partial_cmp(&self, other: &Self) -> Option { + Some(self.cmp(other)) + } +} + +impl Ord for Version { + /// SemVer precedence: numbers, then "a prerelease is lower", then the identifiers. + fn cmp(&self, other: &Self) -> std::cmp::Ordering { + let core = (self.major, self.minor, self.patch).cmp(&(other.major, other.minor, other.patch)); + if core != std::cmp::Ordering::Equal { + return core; + } + match (self.pre.is_empty(), other.pre.is_empty()) { + (true, true) => std::cmp::Ordering::Equal, + (true, false) => std::cmp::Ordering::Greater, + (false, true) => std::cmp::Ordering::Less, + (false, false) => pre_cmp(&self.pre, &other.pre), + } + } +} + +/// Identifier by identifier: numeric ones compare as numbers and rank below alphanumeric ones; a +/// shorter list of otherwise equal identifiers ranks lower (`1.0.0-rc` < `1.0.0-rc.1`). +fn pre_cmp(a: &[String], b: &[String]) -> std::cmp::Ordering { + for (x, y) in a.iter().zip(b) { + let nx = x.bytes().all(|c| c.is_ascii_digit()); + let ny = y.bytes().all(|c| c.is_ascii_digit()); + let ord = match (nx, ny) { + (true, true) => match (x.parse::(), y.parse::()) { + (Ok(a), Ok(b)) => a.cmp(&b), + _ => x.cmp(y), + }, + (true, false) => std::cmp::Ordering::Less, + (false, true) => std::cmp::Ordering::Greater, + (false, false) => x.cmp(y), + }; + if ord != std::cmp::Ordering::Equal { + return ord; + } + } + a.len().cmp(&b.len()) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn v(s: &str) -> Version { + Version::parse(s).unwrap_or_else(|e| panic!("{s}: {e}")) + } + + #[test] + fn parses_the_shapes_we_publish() { + assert_eq!(v("1.2.3").to_text(), "1.2.3"); + assert_eq!(v("v1.2.3").to_text(), "1.2.3"); + assert_eq!(v("V1.2.3").to_text(), "1.2.3"); + assert_eq!(v(" 1.2.3 ").to_text(), "1.2.3"); + assert_eq!(v("1.2.3-rc.1").to_text(), "1.2.3-rc.1"); + assert_eq!(v("1.2.3+build.5").to_text(), "1.2.3"); + assert_eq!(v("1.2.0-rc.1+sha.abc").to_text(), "1.2.0-rc.1"); + assert_eq!(v("0.7.0").to_text(), "0.7.0"); + } + + #[test] + fn refuses_what_is_not_a_version() { + for bad in [ + "", + "v", + "1", + "1.2", + "1.2.3.4", + "nightly", + "1.2.x", + "01.2.3", + "1.02.3", + "1.2.03", + "1.2.3-", + "1.2.3+", + "1.2.3-rc..1", + "1.2.3-rc.1!", + "1.2.3+ab cd", + ] { + assert!(Version::parse(bad).is_err(), "{bad} should not parse"); + } + } + + #[test] + fn orders_like_semver() { + assert!(v("1.2.3") > v("1.2.2")); + assert!(v("2.0.0") > v("1.99.99")); + assert!(v("1.2.3") > v("1.2.3-rc.1"), "a release outranks its prerelease"); + assert!(v("1.2.3-rc.2") > v("1.2.3-rc.1")); + assert!(v("1.2.3-rc.1") > v("1.2.3-beta")); + assert!(v("1.2.3-beta.2") > v("1.2.3-beta.1")); + assert!(v("1.2.3-beta.10") > v("1.2.3-beta.9"), "numeric identifiers compare as numbers"); + assert!(v("1.2.3-rc") < v("1.2.3-rc.1")); + assert!(v("1.2.3-1") < v("1.2.3-alpha"), "numeric identifiers rank below alphanumeric ones"); + assert_eq!(v("1.2.3+a").cmp(&v("1.2.3+b")), std::cmp::Ordering::Equal, "build metadata is ignored"); + } + + #[test] + fn current_is_this_build() { + assert_eq!(Version::current().to_text(), env!("CARGO_PKG_VERSION")); + assert!(Version::current() >= Version::current()); + } + + #[test] + fn prerelease_is_reported() { + assert!(v("1.2.3").is_release()); + assert!(!v("1.2.3-rc.1").is_release()); + assert_eq!(v("1.2.3-rc.1").prerelease(), ["rc".to_string(), "1".to_string()]); + } +} diff --git a/docs/manual/troubleshooting.md b/docs/manual/troubleshooting.md index 3612ef85cc..0cd94f2f5d 100644 --- a/docs/manual/troubleshooting.md +++ b/docs/manual/troubleshooting.md @@ -47,6 +47,23 @@ and relinks them. Their edits and metadata are safe in the catalog meanwhile. - File → Test Catalog Integrity checks the store; File → Restore Library from Backup… or opening a copy from `backups/` gets you back to the last good state. +## Updating the app + +Help → Check for Updates… reads the project's release feed and, when something newer exists, offers to +download it for this system and install it; the app restarts afterwards. Things that can go wrong: + +- "Could not reach the release server" or "the release server answered 403": no internet, a proxy, or GitHub's + rate limit. The check uses the release's `latest.json` first, which usually still works; try again later. +- "Release X has no download for this system": that release has no file for this platform (a platform added + after it was published, or one we don't package). Get it from the project's releases page, which the dialog + links to. +- The download is checked against the size the release states and, when the release publishes + `SHA256SUMS.txt`, against that SHA-256. A file that fails the check is deleted and nothing is installed. +- A tarball or zip (Linux riscv64, FreeBSD, or a Windows portable build) is downloaded and its folder shown: + quit the app and unpack it over the installation yourself. +- Turning off "Check for updates when the app starts" stops the automatic check; Help → Check for Updates… + still works by hand. The setting lives in the app's own settings folder (`updates.json`), not in a catalog. + ## Chinese or Japanese text shows boxes The build was made without craft-fonts. Release builds always include it; for source builds set @@ -60,5 +77,7 @@ skipped when the session starts unless you turn that off ([tethering.md](tetheri ## Network features -Map tiles, reverse geocoding, model downloads, Immich, SFTP upload and IPP printing are the only things that use -the network, and each asks or is configured explicitly. Behind a proxy or offline, the rest of the app works. +Two things reach the network on their own: the update check (once, a few seconds after start-up, unless +"Check for updates when the app starts" is off — see above), and nothing else. Map tiles, reverse geocoding, +model downloads, Immich, SFTP upload and IPP printing all use the network too, and each asks or is configured +explicitly. Behind a proxy or offline, the rest of the app works. diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index 32db2c9d60..f10060f10c 100644 --- a/docs/parity-checklist.md +++ b/docs/parity-checklist.md @@ -50,13 +50,13 @@ cited here still exists. Formerly docs/parity.md. | V. Preferences (PREF) | 6 | 2 | 2 | 2 | 1/1 (100%) | 4/5 (80%) | | W. Cloud & AI infrastructure (CLOUD / AI) | 1 | 0 | 1 | 2 | — | — | | X. Cross-cutting behaviours (BEHAV) | 23 | 6 | 1 | 1 | 8/8 (100%) | 7/10 (70%) | -| Y. Menus | 84 | 0 | 4 | 8 | 47/47 (100%) | 23/23 (100%) | +| Y. Menus | 85 | 0 | 4 | 8 | 47/47 (100%) | 23/23 (100%) | | Z. Keyboard shortcuts (desktop) | 76 | 3 | 3 | 1 | 49/52 (94%) | 23/24 (96%) | | Lightroom Classic extras | 102 | 18 | 5 | 0 | — | 34/38 (89%) | | IMM. Immich integration | 10 | 0 | 0 | 0 | — | 6/6 (100%) | -| **Total** | 488 | 57 | 38 | 27 | 194/201 (97%) | 161/175 (92%) | +| **Total** | 489 | 57 | 38 | 27 | 194/201 (97%) | 161/175 (92%) | -Weighted completion (✅ = 1, 🟡 = ½, 🚫 left out): **88.6%** of 583 in-scope rows — P0 98.3% of 201 · P1 95.7% of 175 · P2 73.2% of 205. +Weighted completion (✅ = 1, 🟡 = ½, 🚫 left out): **88.6%** of 584 in-scope rows — P0 98.3% of 201 · P1 95.7% of 175 · P2 73.3% of 206. ## Top gaps and shortcut notes @@ -644,6 +644,7 @@ visible menu bar yet: the menu model is only exposed through the control channel | MENU-HELP-HELP | Help | P2 | ✅ | `cmd:app.help` | opens the documentation | | MENU-HELP-TUTORIALS | Tutorials | OOS | 🚫 | | | | MENU-HELP-WHATSNEW | What's new | P2 | ✅ | `cmd:app.whatsNew` | | +| MENU-HELP-UPDATES | Check for updates | P2 | ✅ | `cmd:app.checkForUpdates`, `cmd:update.status`, `cmd:update.check`, `cmd:update.download`, `cmd:update.install`, `cmd:update.prefs`, `crates/updater`, `crates/engine/src/update.rs`, `crates/ui-egui/src/panels/update.rs` | an extra (the reference app updates through its own service): Help ▸ Check for Updates… reads the release feed (the `latest.json` the release publishes, else GitHub's Releases API, else `{env}_UPDATE_URL`), compares versions, shows the notes and what installing will do, downloads the asset for the platform (resumable, size- and SHA-256-checked, in the activity stack) and installs it — the Windows MSI runs, the macOS disk image is mounted and its app copied over this one, an AppImage replaces itself; a tarball or zip is laid out for a manual install. One check runs a few seconds after start-up unless turned off; a release already skipped is not offered again | | MENU-HELP-SHORTCUTS | Keyboard shortcuts | P1 | ✅ | `cmd:app.shortcuts` | | | MENU-HELP-FEEDBACK | Send feedback | P2 | ✅ | `cmd:app.feedback` | opens a new issue on the project's GitHub | | MENU-HELP-LOGFOLDER | Open log folder | P2 | ✅ | `cmd:app.openLogFolder` | an extra (the reference app has no such item): Help ▸ Open Log Folder reveals the app log in `logs/` in the system file manager (Finder, Explorer, or the folder on Linux); off on the web and in `--memory` sessions, which keep no log (issue #260) | diff --git a/docs/releasing.md b/docs/releasing.md index b320d0427a..9c61620c3f 100644 --- a/docs/releasing.md +++ b/docs/releasing.md @@ -23,6 +23,24 @@ still apply. The workflow replaces assets when it updates an existing draft. It stops rather than overwriting a release that has already been published, so bump the version before producing another release. +## The update feed + +Each release carries a `latest.json` beside its artifacts. It is what Help ▸ Check for Updates… reads +(the in-app updater, [`crates/updater`](../crates/updater)): the version, the date, and one entry per +artifact with its file name, download URL, size and SHA-256. The app reads +`https://github.com///releases/latest/download/latest.json` first and falls back to GitHub's +Releases API, so the check keeps working when the API is rate-limited; `_UPDATE_URL` points a +build at another feed (a mirror, a fork, a local file server). + +The `release` job builds the manifest from the downloaded artifacts and the checksums it just computed, so +only what is actually attached to the release is offered. It is uploaded with the rest of the assets and +replaced on every run of the draft. Nothing else has to be maintained by hand: a new platform is offered as +soon as its artifact name carries the OS and architecture slugs the pipeline already uses +(`---…`). + +Prerelease tags get a manifest too (with `prerelease: true`): the app only offers one when +"Include prereleases" is ticked, so a release candidate never reaches someone on a stable build. + ## Builds and artifacts Release jobs build macOS universal, Windows x86/x64/ARM64, Linux x86_64/aarch64/riscv64, FreeBSD x86_64, diff --git a/xtask/src/layers.rs b/xtask/src/layers.rs index a7b3890cf1..007fa9ef50 100644 --- a/xtask/src/layers.rs +++ b/xtask/src/layers.rs @@ -42,6 +42,7 @@ pub const TABLE: &[(&str, Class)] = &[ ("audio-out", Class::Layer(0)), ("fetch", Class::Layer(0)), ("net", Class::Layer(0)), + ("updater", Class::Layer(0)), ("credentials", Class::Layer(0)), ("hash", Class::Layer(0)), ("psd", Class::Standalone), @@ -105,6 +106,8 @@ pub const INTRA_LAYER_ORDER: &[&[&str]] = &[ &["brand", "sysmem"], &["brand", "fetch"], &["brand", "net"], + // the updater reads the release feed over the network crate, for the brand's repository + &["brand", "net", "updater"], &["brand", "credentials"], &["brand", "heif"], &["brand", "audio-out"],