From d26de760971383ee2405ad5f1e2785c70cb8b252 Mon Sep 17 00:00:00 2001 From: bherbruck Date: Wed, 28 Oct 2026 18:14:57 +0000 Subject: [PATCH] Updates: leave the update to the launcher that manages this copy (#8403) Co-authored-by: Claude Opus 5.5 --- .../pending/update-managed-by-launcher.json | 26 ++++ crates/ui-egui/src/update.rs | 136 ++++++++++++++++- crates/ui-egui/src/update/tests.rs | 140 ++++++++++++++++++ docs/book/src/guide/updates.md | 18 +++ 4 files changed, 319 insertions(+), 1 deletion(-) create mode 100644 assets/locales/pending/update-managed-by-launcher.json diff --git a/assets/locales/pending/update-managed-by-launcher.json b/assets/locales/pending/update-managed-by-launcher.json new file mode 100644 index 000000000..94bda1b01 --- /dev/null +++ b/assets/locales/pending/update-managed-by-launcher.json @@ -0,0 +1,26 @@ +{ + "en": { + "update.managed": "Update available: update SolidCraft in {manager}", + "update.prefs_managed": "This is SolidCraft {version}, managed by {manager}. A check asks GitHub for the latest release and sends nothing else; update SolidCraft in {manager}." + }, + "ar": { + "update.managed": "يتوفر تحديث: حدّث SolidCraft من داخل {manager}", + "update.prefs_managed": "هذا هو SolidCraft {version}، ويديره {manager}. يسأل الفحص GitHub عن أحدث إصدار ولا يرسل شيئًا آخر؛ حدّث SolidCraft من داخل {manager}." + }, + "he": { + "update.managed": "יש עדכון זמין: עדכנו את SolidCraft ב-{manager}", + "update.prefs_managed": "זהו SolidCraft {version}, בניהול {manager}. הבדיקה שואלת את GitHub מהי הגרסה האחרונה ולא שולחת דבר נוסף; עדכנו את SolidCraft ב-{manager}." + }, + "ja": { + "update.managed": "アップデートがあります。{manager} で SolidCraft を更新してください", + "update.prefs_managed": "これは {manager} が管理している SolidCraft {version} です。確認では GitHub に最新リリースを問い合わせるだけで、ほかには何も送信しません。SolidCraft は {manager} で更新してください。" + }, + "vi": { + "update.managed": "Có bản cập nhật: hãy cập nhật SolidCraft trong {manager}", + "update.prefs_managed": "Đây là SolidCraft {version}, do {manager} quản lý. Lần kiểm tra chỉ hỏi GitHub về bản phát hành mới nhất và không gửi gì khác; hãy cập nhật SolidCraft trong {manager}." + }, + "zh": { + "update.managed": "有可用更新:请在 {manager} 中更新 SolidCraft", + "update.prefs_managed": "这是由 {manager} 管理的 SolidCraft {version}。检查时只向 GitHub 询问最新版本,不会发送其他任何内容;请在 {manager} 中更新 SolidCraft。" + } +} diff --git a/crates/ui-egui/src/update.rs b/crates/ui-egui/src/update.rs index c6bdb5916..11a46850f 100644 --- a/crates/ui-egui/src/update.rs +++ b/crates/ui-egui/src/update.rs @@ -4,6 +4,10 @@ //! appears in the application bar beside Report a bug; it opens a small window with the version, //! the release notes and Download, Skip this version and Remind me later. //! +//! A launcher (ArtCraft Launcher) can manage this copy: `SOLIDCRAFT_MANAGED_BY=`, or its +//! `installed.json` records this installation. The checks run as before, but the window only says +//! to update SolidCraft in that launcher: no Update now, no AppImage replacement, no Download. +//! //! The request is the only thing sent: no identifiers, no usage data. A short timeout keeps it //! from hanging, a failed check (offline, rate limited) stays silent and is retried later, and //! development builds never check. Turning off Preferences ▸ General ▸ Check for updates @@ -278,6 +282,113 @@ fn msi_install_dir() -> Option { None } +// ---- managed by a launcher -------------------------------------------------------------------- + +/// Set by a launcher that installed and updates this copy; the value is its display name +/// ("ArtCraft Launcher"). The window then points to it instead of replacing files itself. +pub const MANAGED_ENV: &str = "SOLIDCRAFT_MANAGED_BY"; + +/// The ArtCraft Launcher's name, shown when its install record (not the variable) says it manages this copy. +const LAUNCHER_NAME: &str = "ArtCraft Launcher"; + +/// The key the launcher files SolidCraft under in its `installed.json`. +const LAUNCHER_APP_ID: &str = "solidcraft"; + +/// The longest manager name shown (the variable is untrusted text). +const MAX_MANAGER_NAME: usize = 64; + +/// A launcher's record file is a few KB; this is room for a hundred apps. +#[cfg(not(target_arch = "wasm32"))] +const MAX_RECORD_FILE: u64 = 1 << 20; + +/// `a` is `b` or inside it. Slashes, a trailing separator and Windows' `\\?\` prefix don't count; +/// case counts only where the file system ignores it. +fn same_or_inside(a: &Path, b: &Path, ignore_case: bool) -> bool { + let norm = |p: &Path| { + let mut t = p.to_string_lossy().replace('\\', "/"); + if ignore_case { + t = t.to_lowercase(); + } + t.strip_prefix("//?/").map_or(t.clone(), str::to_string).trim_end_matches('/').to_string() + }; + let (a, b) = (norm(a), norm(b)); + // The bare root (`/`, `C:\`) would hold every install. + !b.is_empty() && !b.ends_with(':') && (a == b || a.strip_prefix(&b).is_some_and(|rest| rest.starts_with('/'))) +} + +/// Whether the launcher's `installed.json` (`bytes`) records this installation: its `solidcraft` +/// entry's `path` (the exe, the AppImage, the `.app`, or the folder of an unpacked tarball) is one +/// of `places` or contains one. +pub fn record_matches(bytes: &[u8], places: &[PathBuf], ignore_case: bool) -> bool { + let Ok(json) = serde_json::from_slice::(bytes) else { return false }; + let Some(path) = json.get("apps").and_then(|a| a.get(LAUNCHER_APP_ID)).and_then(|r| r.get("path")).and_then(Value::as_str) else { + return false; + }; + // A relative path would claim whatever it is read against. (Not `Path::is_absolute`: a record + // written on Windows has to read as absolute everywhere the tests run.) + let absolute = path.starts_with(['/', '\\']) + || path.as_bytes().get(1..3).is_some_and(|d| d.first() == Some(&b':') && d.get(1).is_some_and(|c| matches!(c, b'/' | b'\\'))); + absolute && places.iter().any(|p| same_or_inside(p, Path::new(path), ignore_case)) +} + +/// Where the launcher keeps `installed.json` for this user, as the launcher itself works it out +/// (`/artcraft-launcher`, or `ArtCraft Launcher` on Windows and macOS). +fn launcher_record_path(os: &str, env: &dyn Fn(&str) -> Option) -> Option { + let var = |k: &str| env(k).filter(|v| !v.trim().is_empty()).map(PathBuf::from); + let (base, dir) = match os { + "windows" => (var("LOCALAPPDATA")?, "ArtCraft Launcher"), + "macos" => (var("HOME")?.join("Library/Application Support"), "ArtCraft Launcher"), + _ => (var("XDG_DATA_HOME").or_else(|| var("HOME").map(|h| h.join(".local/share")))?, "artcraft-launcher"), + }; + Some(base.join(dir).join("installed.json")) +} + +/// What manages this copy, if anything: the variable's value, else "ArtCraft Launcher" when its +/// install record names this installation. Read-only: nothing is written or created. +/// `read` returns a file's bytes. +pub fn managed_by( + os: &str, + env: &dyn Fn(&str) -> Option, + exe: Option<&Path>, + kind: &InstallKind, + read: &dyn Fn(&Path) -> Option>, +) -> Option { + if let Some(name) = env(MANAGED_ENV) { + let name: String = name.chars().filter(|c| !c.is_control()).take(MAX_MANAGER_NAME).collect(); + if !name.trim().is_empty() { + return Some(name.trim().to_string()); + } + } + let mut places: Vec = exe.map(Path::to_path_buf).into_iter().collect(); + if let InstallKind::AppImage(p) | InstallKind::MacApp(p) = kind { + places.push(p.clone()); + } + // The launcher runs an unpacked tarball with its own HOME, so the usual place is out of reach: + // `/apps/solidcraft/…` has the record two levels up. + let beside_apps = exe.into_iter().flat_map(Path::ancestors).find(|a| a.file_name().is_some_and(|n| n == "apps")).and_then(Path::parent); + let records = beside_apps.map(|d| d.join("installed.json")).into_iter().chain(launcher_record_path(os, env)); + let ignore_case = matches!(os, "windows" | "macos"); + records.filter_map(|path| read(&path)).any(|bytes| record_matches(&bytes, &places, ignore_case)).then(|| LAUNCHER_NAME.to_string()) +} + +/// This machine's manager, looked up once. +#[cfg(not(target_arch = "wasm32"))] +fn this_managed_by(kind: &InstallKind) -> Option { + use std::io::Read; + let env = |k: &str| std::env::var(k).ok(); + let read = |p: &Path| { + let mut bytes = Vec::new(); + std::fs::File::open(p).ok()?.take(MAX_RECORD_FILE).read_to_end(&mut bytes).ok()?; + Some(bytes) + }; + managed_by(std::env::consts::OS, &env, std::env::current_exe().ok().as_deref(), kind, &read) +} + +#[cfg(target_arch = "wasm32")] +fn this_managed_by(_kind: &InstallKind) -> Option { + None +} + impl InstallKind { /// The package manager updates it: Download isn't the way (the window shows the command). pub fn system_managed(&self) -> bool { @@ -525,6 +636,9 @@ pub enum Status { pub struct Updater { /// The installation, looked up at the first frame. pub kind: Option, + /// What manages this copy (`SOLIDCRAFT_MANAGED_BY`, or a launcher's record), looked up with + /// the installation: Some(None) is "nothing does". + pub managed: Option>, pub status: Status, /// The newest release found (whether or not it is offered). pub release: Option, @@ -554,6 +668,15 @@ impl Updater { pub fn kind(&mut self) -> &InstallKind { self.kind.get_or_insert_with(this_install) } + + /// The launcher that updates this copy, if one does (looked up on first use). + pub fn managed_by(&mut self) -> Option<&str> { + if self.managed.is_none() { + let kind = self.kind().clone(); + self.managed = Some(this_managed_by(&kind)); + } + self.managed.as_ref()?.as_deref() + } } /// The Update button shows. @@ -678,6 +801,10 @@ fn poll(app: &mut SolveApp) { /// How this installation updates in place, when the host can download (None: Download only). pub fn install_method(app: &mut SolveApp) -> Option { + // A launcher updates its copies itself: no Update now, no replacing the AppImage under it. + if app.updater.managed_by().is_some() { + return None; + } if app.services.http_get.is_none() || app.services.http_download.is_none() { return None; } @@ -802,6 +929,7 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) { }; let kind = app.updater.kind().clone(); let install = install_method(app); + let managed = app.updater.managed_by().map(str::to_string); let arch = std::env::consts::ARCH; let t = Tokens::get(); let one_click = install.is_some() && !matches!(app.updater.installed, Some(Err(_))); @@ -824,6 +952,8 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) { State::Downloading => ("", crate::i18n::tr("ui.cancel"), None), State::Restart => (crate::i18n::tr("update.restart"), crate::i18n::tr("update.restart_later"), None), State::Started => ("", crate::i18n::tr("ui.close"), None), + // Managed: nothing here installs or downloads; the launcher does. + State::Offer if managed.is_some() => ("", crate::i18n::tr("update.later"), Some(crate::i18n::tr("update.skip"))), State::Offer => (primary, crate::i18n::tr("update.later"), Some(crate::i18n::tr("update.skip"))), }; let id = egui::Id::new("sc_update"); @@ -843,7 +973,9 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) { }); }); let asset = release.asset_for(&kind, arch).map(|a| a.name.clone()); - if let Some(cmd) = kind.update_command(asset.as_deref()) { + if let Some(manager) = &managed { + ui_kit::text(ui, &crate::i18n::format("update.managed", &[("manager", manager)]), ui_kit::Text::Report("managed", false)); + } else if let Some(cmd) = kind.update_command(asset.as_deref()) { let how = match kind { InstallKind::Deb | InstallKind::Rpm | InstallKind::Snap { store: false } => "update.package_hint", _ => "update.system_hint", @@ -978,6 +1110,8 @@ pub fn prefs_rows(app: &mut SolveApp, ui: &mut egui::Ui) { } let note = if kind == InstallKind::Web { crate::i18n::tr("update.prefs_web").to_string() + } else if can && let Some(manager) = app.updater.managed_by().map(str::to_string) { + crate::i18n::format("update.prefs_managed", &[("version", current_version()), ("manager", &manager)]) } else if can { crate::i18n::format("update.prefs_note", &[("version", current_version()), ("kind", kind.label())]) } else if let InstallKind::Flatpak(id) = &kind { diff --git a/crates/ui-egui/src/update/tests.rs b/crates/ui-egui/src/update/tests.rs index 690d70b21..dc250a1be 100644 --- a/crates/ui-egui/src/update/tests.rs +++ b/crates/ui-egui/src/update/tests.rs @@ -546,3 +546,143 @@ fn web_preferences_explain_reload_without_update_controls() { assert!(!texts.iter().any(|t| t == crate::i18n::tr("update.check_now")), "{texts:?}"); assert!(texts.iter().any(|t| t == crate::i18n::tr("update.prefs_web")), "{texts:?}"); } + +fn no_env(_: &str) -> Option { + None +} + +fn record(path: &str) -> Vec { + json!({"apps": {"solidcraft": {"version": "0.25.1", "kind": "AppImage", "path": path, "installed_at": 1}}}).to_string().into_bytes() +} + +#[test] +fn the_variable_names_the_manager() { + let nothing = |_: &Path| None; + let kind = InstallKind::LinuxTarball; + let with = |value: &'static str| { + let env = move |k: &str| (k == MANAGED_ENV).then(|| value.to_string()); + managed_by("linux", &env, Some(Path::new("/opt/sc/solidcraft")), &kind, ¬hing) + }; + assert_eq!(with("ArtCraft Launcher").as_deref(), Some("ArtCraft Launcher")); + assert_eq!(with(" Other \u{7}Manager\n").as_deref(), Some("Other Manager"), "padding and control characters are dropped"); + assert_eq!(with(" "), None, "an empty value is not a manager"); + assert_eq!(with(&"x".repeat(500).leak()[..]).map(|n| n.len()), Some(64), "a long name is cut"); + assert_eq!(managed_by("linux", &no_env, Some(Path::new("/opt/sc/solidcraft")), &kind, ¬hing), None); +} + +#[test] +fn the_launchers_record_marks_the_install_it_made() { + let exe = Path::new("/home/me/Apps/SolidCraft.AppImage"); + let appimage = InstallKind::AppImage(exe.to_path_buf()); + let env = |k: &str| (k == "HOME").then(|| "/home/me".to_string()); + let seen = std::cell::RefCell::new(Vec::new()); + let read = |bytes: Vec| { + let seen = &seen; + move |p: &Path| { + seen.borrow_mut().push(p.to_path_buf()); + Some(bytes.clone()) + } + }; + // The AppImage the launcher recorded; the running executable is inside its mount. + let run = |path: &str| managed_by("linux", &env, Some(Path::new("/tmp/.mount_SolidXYZ/usr/bin/solidcraft")), &appimage, &read(record(path))); + assert_eq!(run("/home/me/Apps/SolidCraft.AppImage").as_deref(), Some("ArtCraft Launcher")); + assert_eq!(seen.borrow().as_slice(), [PathBuf::from("/home/me/.local/share/artcraft-launcher/installed.json")]); + // Another copy, a prefix that is not a folder of ours, the root and a relative path are not ours. + assert_eq!(run("/home/me/Apps/Other.AppImage"), None); + assert_eq!(run("/home/me/Apps/SolidCraft.AppImage.old"), None); + assert_eq!(run("/"), None); + assert_eq!(run("Apps/SolidCraft.AppImage"), None); + // No record, a damaged one, one without SolidCraft, and a record file of any other shape. + let one = |bytes: &'static [u8]| managed_by("linux", &env, Some(exe), &appimage, &|_: &Path| Some(bytes.to_vec())); + assert_eq!(one(b"{not json"), None); + assert_eq!(one(br#"{"apps": {"photocraft": {"path": "/home/me/Apps/SolidCraft.AppImage"}}}"#), None); + assert_eq!(one(br#"{"apps": {"solidcraft": {"path": 7}}}"#), None); + assert_eq!(one(b"[]"), None); + assert_eq!(managed_by("linux", &env, Some(exe), &appimage, &|_: &Path| None), None); + // XDG_DATA_HOME moves the record. + let xdg = |k: &str| (k == "XDG_DATA_HOME").then(|| "/data".to_string()); + let paths = std::cell::RefCell::new(Vec::new()); + managed_by("linux", &xdg, Some(exe), &appimage, &|p: &Path| { + paths.borrow_mut().push(p.to_path_buf()); + None + }); + assert_eq!(paths.into_inner(), [PathBuf::from("/data/artcraft-launcher/installed.json")]); +} + +#[test] +fn the_record_matches_folders_bundles_and_windows_paths() { + let nothing_else = |bytes: Vec| move |_: &Path| Some(bytes.clone()); + // An unpacked tarball: the record names the folder, and the launcher's own HOME is no help, + // so the record is found beside the `apps` folder the app runs from. + let exe = Path::new("/home/me/.local/share/artcraft-launcher/apps/solidcraft/bin/solidcraft"); + let read = |p: &Path| { + (p == Path::new("/home/me/.local/share/artcraft-launcher/installed.json")) + .then(|| record("/home/me/.local/share/artcraft-launcher/apps/solidcraft")) + }; + let home = |k: &str| (k == "HOME").then(|| "/home/me/.local/share/artcraft-launcher/apps/solidcraft/home".to_string()); + assert_eq!(managed_by("linux", &home, Some(exe), &InstallKind::LinuxTarball, &read).as_deref(), Some("ArtCraft Launcher")); + // macOS: the bundle. + let bundle = PathBuf::from("/Applications/SolidCraft.app"); + let mac = InstallKind::MacApp(bundle.clone()); + let exe = Path::new("/Applications/SolidCraft.app/Contents/MacOS/solidcraft"); + let home = |k: &str| (k == "HOME").then(|| "/Users/me".to_string()); + let read = |p: &Path| { + assert_eq!(p, Path::new("/Users/me/Library/Application Support/ArtCraft Launcher/installed.json")); + Some(record("/Applications/SolidCraft.app")) + }; + assert_eq!(managed_by("macos", &home, Some(exe), &mac, &read).as_deref(), Some("ArtCraft Launcher")); + // Windows: case and the verbatim prefix don't matter, and the record is under LOCALAPPDATA. + let local = |k: &str| (k == "LOCALAPPDATA").then(|| r"C:\Users\me\AppData\Local".to_string()); + let exe = Path::new(r"C:\Users\me\AppData\Local\Programs\SolidCraft\solidcraft.exe"); + let read = nothing_else(record(r"\\?\c:\users\me\appdata\local\programs\solidcraft\SOLIDCRAFT.EXE")); + assert_eq!(managed_by("windows", &local, Some(exe), &InstallKind::WindowsExe, &read).as_deref(), Some("ArtCraft Launcher")); + let read = nothing_else(record(r"C:\Users\me\AppData\Local\Programs\SolidCraft2")); + assert_eq!(managed_by("windows", &local, Some(exe), &InstallKind::WindowsExe, &read), None, "a folder whose name only starts the same"); + // Linux paths are case-sensitive. + let read = nothing_else(record("/OPT/SC")); + assert_eq!(managed_by("linux", &no_env, Some(Path::new("/opt/sc/solidcraft")), &InstallKind::LinuxTarball, &read), None); +} + +/// A harness with a newer release found and the Update window open, on an AppImage that a +/// launcher may manage. The host can download, so the one-click update is on offer unless managed. +fn open_update_window(managed: Option<&str>) -> (crate::scenario::Harness, Scratch) { + let dir = scratch(); + let (feed, _) = next_release_feed(&dir.0); + let mut h = crate::scenario::Harness::new(); + let get: HttpGet = Arc::new(|_| Err(FetchError::Failed("offline".into()))); + let download: install::HttpDownload = Arc::new(|_, _, _| Err(FetchError::Failed("offline".into()))); + h.app.services.http_get = Some(get); + h.app.services.http_download = Some(download); + h.app.updater.kind = Some(InstallKind::AppImage("/home/me/SolidCraft.AppImage".into())); + h.app.updater.managed = Some(managed.map(str::to_string)); + h.app.updater.feed = Some(feed); + h.frame(); + wait_for_check(&mut h); + h.frames(2); + h.app.updater.open = true; + h.frames(3); + (h, dir) +} + +#[test] +fn a_managed_install_points_to_its_manager_instead_of_updating_itself() { + let (mut h, _dir) = open_update_window(Some("ArtCraft Launcher")); + assert_eq!(install_method(&mut h.app), None, "no AppImage self-replace"); + assert!(h.widget("Update available: update SolidCraft in ArtCraft Launcher").is_some()); + for gone in ["Update now", "Download", "Open release page"] { + assert!(h.widget(gone).is_none(), "{gone} is not offered"); + } + assert!(h.widget("Skip this version").is_some() && h.widget("Remind me later").is_some()); + // It still checked and still shows the pill. + assert!(h.app.updater.release.is_some() && offered(&h.app).is_some()); + assert!(crate::scenario::rect_of("titlebar:update").is_some()); +} + +#[test] +fn an_unmanaged_install_updates_itself_as_before() { + let (mut h, _dir) = open_update_window(None); + assert_eq!(install_method(&mut h.app), Some(install::Method::AppImage("/home/me/SolidCraft.AppImage".into()))); + assert!(h.widget("Update now").is_some()); + assert!(h.widget("Download").is_some()); + assert!(h.widget("Update available: update SolidCraft in ArtCraft Launcher").is_none()); +} diff --git a/docs/book/src/guide/updates.md b/docs/book/src/guide/updates.md index b49b37119..088cdd550 100644 --- a/docs/book/src/guide/updates.md +++ b/docs/book/src/guide/updates.md @@ -90,6 +90,24 @@ no check controls for them. The browser app updates itself: reload the page to g version. When the network is unavailable, or the update can't finish downloading in time, the saved version opens instead, and the download continues for the next reload. +## Managed by a launcher + +When a launcher such as the ArtCraft Launcher installed SolidCraft, it also updates it. SolidCraft +notices this in two ways: + +- the environment variable `SOLIDCRAFT_MANAGED_BY` is set; its value is the launcher's name, for + example `ArtCraft Launcher`, and +- the ArtCraft Launcher's `installed.json` (in its per-user data folder, read-only) lists this + SolidCraft: its recorded path is this executable, this AppImage or `.app`, or the folder this + executable was unpacked into. + +SolidCraft then still checks for a newer release, and the pill and **Check now** work as before, but +the window says **Update available: update SolidCraft in ArtCraft Launcher** and offers only +**Skip this version** and **Remind me later**. There is no **Update now**, **Download** or +AppImage replacement, so the launcher's record of what is installed stays right. Without the +variable or a record, nothing changes. Setting `SOLIDCRAFT_UPDATE_CHECK=0` still turns the checks +off. + ## Which file Download gets Releases attach the main packages under fixed names (see [releasing](https://github.com/bherbruck/solidcraft/blob/main/docs/releasing.md)),