SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.
Update now installs the newest release, checked when pressed (#7724) (#7725)
raykholof03d0a20bdba
diff --git a/assets/locales/pending/update-refresh-latest.json b/assets/locales/pending/update-refresh-latest.jsonnew file mode 100644index 0000000000..e81f4fdd85--- /dev/null+++ b/assets/locales/pending/update-refresh-latest.json@@ -0,0 +1,42 @@+{+ "en": {+ "update.refresh_checking": "Checking for the newest release…",+ "update.refresh_fallback": "Could not check for a newer release; updating to {version}, found earlier.",+ "update.refresh_selected": "Updating to {version}."+ },+ "ar": {+ "update.refresh_checking": "جارٍ البحث عن أحدث إصدار…",+ "update.refresh_fallback": "تعذّر البحث عن إصدار أحدث؛ سيتم التحديث إلى {version} الذي عُثر عليه سابقًا.",+ "update.refresh_selected": "جارٍ التحديث إلى {version}."+ },+ "de": {+ "update.refresh_checking": "Neueste Version wird gesucht…",+ "update.refresh_fallback": "Die Suche nach einer neueren Version ist fehlgeschlagen; die zuvor gefundene Version {version} wird installiert.",+ "update.refresh_selected": "Version {version} wird installiert."+ },+ "he": {+ "update.refresh_checking": "בודק אם יש גרסה חדשה יותר…",+ "update.refresh_fallback": "לא ניתן היה לבדוק אם יש גרסה חדשה יותר; מעדכן לגרסה {version} שנמצאה קודם.",+ "update.refresh_selected": "מעדכן לגרסה {version}."+ },+ "ja": {+ "update.refresh_checking": "最新のリリースを確認中…",+ "update.refresh_fallback": "新しいリリースを確認できませんでした。以前見つかった {version} に更新します。",+ "update.refresh_selected": "{version} に更新中。"+ },+ "ko": {+ "update.refresh_checking": "최신 릴리스 확인 중…",+ "update.refresh_fallback": "새 릴리스를 확인하지 못했습니다. 이전에 찾은 {version}(으)로 업데이트합니다.",+ "update.refresh_selected": "{version}(으)로 업데이트 중."+ },+ "vi": {+ "update.refresh_checking": "Đang kiểm tra bản phát hành mới nhất…",+ "update.refresh_fallback": "Không thể kiểm tra bản phát hành mới hơn; đang cập nhật lên {version} đã tìm thấy trước đó.",+ "update.refresh_selected": "Đang cập nhật lên {version}."+ },+ "zh": {+ "update.refresh_checking": "正在检查最新版本…",+ "update.refresh_fallback": "无法检查更新的版本;将更新至先前找到的 {version}。",+ "update.refresh_selected": "正在更新至 {version}。"+ }+}diff --git a/crates/ui-egui/src/update.rs b/crates/ui-egui/src/update.rsindex 3a134a1d3e..fc302f532c 100644--- a/crates/ui-egui/src/update.rs+++ b/crates/ui-egui/src/update.rs@@ -55,6 +55,7 @@ pub const MANUAL_COOLDOWN_S: f64 = 30.0;pub const RETRY_AFTER_FAILURE_S: f64 = 3600.0;/// Caps on what a release response may hold (it comes from the network).const MAX_NOTES: usize = 64 * 1024;+const MAX_RELEASE_BYTES: usize = 4 * 1024 * 1024;const MAX_ASSETS: usize = 400;/// The room the Update pill's long label leaves for the document tabs.const TAB_ROOM: f32 = 300.0;@@ -493,6 +494,9 @@ impl Release {/// A `releases/latest` answer. Drafts and prereleases are refused (GitHub never returns them/// there, but the answer comes from the network).pub fn parse(json: &[u8]) -> Result<Release, FetchError> {+ if json.len() > MAX_RELEASE_BYTES {+ return Err(FetchError::Failed("release response is too large".into()));+ }let v: Value = serde_json::from_slice(json).map_err(|e| FetchError::Failed(format!("unexpected answer from GitHub: {e}")))?;let s = |k: &str| v.get(k).and_then(Value::as_str).unwrap_or_default().to_string();if v.get("draft").and_then(Value::as_bool).unwrap_or(false) || v.get("prerelease").and_then(Value::as_bool).unwrap_or(false) {@@ -713,7 +717,12 @@ pub fn tick(app: &mut SolveApp, ctx: &egui::Context) {poll(app);let now = unix_now();let launch = !app.updater.launch_checked;- if app.updater.rx.is_none() && app.preferences.check_updates && app.preferences.update.due(now, launch) && available(app) {+ if app.updater.job.is_none()+ && app.updater.rx.is_none()+ && app.preferences.check_updates+ && app.preferences.update.due(now, launch)+ && available(app)+ {app.updater.launch_checked = true;start(app, ctx, false);}@@ -734,20 +743,29 @@ pub fn check_now(app: &mut SolveApp, ctx: &egui::Context) {start(app, ctx, true);}+/// Fetch the same bounded feed for automatic checks and an explicit installation.+fn fetch_latest(feed: Option<&Path>, http: Option<&HttpGet>) -> Result<Release, FetchError> {+ use std::io::Read;+ let body = match (feed, http) {+ (Some(path), _) => {+ let file = std::fs::File::open(path).map_err(|e| FetchError::Failed(e.to_string()))?;+ let mut body = Vec::new();+ file.take(MAX_RELEASE_BYTES as u64 + 1).read_to_end(&mut body).map_err(|e| FetchError::Failed(e.to_string()))?;+ body+ }+ (None, Some(get)) => get(LATEST_API)?,+ (None, None) => return Err(FetchError::Failed("no network client".into())),+ };+ Release::parse(&body)+}+fn start(app: &mut SolveApp, ctx: &egui::Context, manual: bool) {let (tx, rx) = std::sync::mpsc::channel();app.updater.status = Status::Checking;app.updater.rx = Some((rx, manual));let feed = app.updater.feed.clone();let http = app.services.http_get.clone();- let fetch = move || -> Result<Release, FetchError> {- let body = match (&feed, &http) {- (Some(path), _) => std::fs::read(path).map_err(|e| FetchError::Failed(format!("{}: {e}", path.display())))?,- (None, Some(get)) => get(LATEST_API)?,- (None, None) => return Err(FetchError::Failed("no network client".into())),- };- Release::parse(&body)- };+ let fetch = move || fetch_latest(feed.as_deref(), http.as_ref());#[cfg(not(target_arch = "wasm32"))]{let ctx = ctx.clone();@@ -788,7 +806,9 @@ fn poll(app: &mut SolveApp) {app.preferences.update.remind_after = 0.0;app.updater.open = true;}- app.updater.release = Some(release);+ if app.updater.job.is_none() && app.updater.release.as_ref().is_none_or(|known| !is_newer(&known.tag, &release.tag)) {+ app.updater.release = Some(release);+ }}Err(e) => {log::info!("update check: {e}");@@ -819,7 +839,7 @@ pub fn install_method(app: &mut SolveApp) -> Option<install::Method> {}}-/// Download, verify and apply the release found (Update now).+/// Re-check the feed, then download, verify and apply the newest release (Update now).pub fn start_install(app: &mut SolveApp, ctx: &egui::Context) {let (Some(release), Some(method), Some(get), Some(download)) =(app.updater.release.clone(), install_method(app), app.services.http_get.clone(), app.services.http_download.clone())@@ -830,6 +850,7 @@ pub fn start_install(app: &mut SolveApp, ctx: &egui::Context) {return;}let kind = app.updater.kind().clone();+ let feed = app.updater.feed.clone();let progress = Arc::new(install::Progress::default());let (tx, rx) = std::sync::mpsc::channel();app.updater.installed = None;@@ -838,7 +859,7 @@ pub fn start_install(app: &mut SolveApp, ctx: &egui::Context) {{let ctx = ctx.clone();let staging = std::env::temp_dir().join("solidcraft-update");- let net = install::Net { get, download };+ let net = install::Net { get, download, feed };let spawned = std::thread::Builder::new().name("update-install".into()).spawn(move || {let result = install::run(&release, &kind, &method, std::env::consts::ARCH, &net, &staging, &progress);let _ = tx.send(result);@@ -851,14 +872,18 @@ pub fn start_install(app: &mut SolveApp, ctx: &egui::Context) {}#[cfg(target_arch = "wasm32")]{- let _ = (ctx, tx, release, method, get, download, kind);+ let _ = (ctx, tx, release, method, get, download, kind, feed);app.updater.job = None;}}fn poll_install(app: &mut SolveApp) {- let Some((rx, _)) = &app.updater.job else { return };- let result = match rx.try_recv() {+ let Some((rx, progress)) = &app.updater.job else { return };+ let received = rx.try_recv();+ if let Some((release, _)) = progress.selection() {+ app.updater.release = Some(release);+ }+ let result = match received {Ok(r) => r,Err(TryRecvError::Empty) => return,Err(TryRecvError::Disconnected) => Err("the update stopped".into()),@@ -991,6 +1016,7 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) {}match (&state, &app.updater.installed, &app.updater.job) {(State::Downloading, _, Some((_, progress))) => {+ ui_kit::text(ui, &progress.message(), ui_kit::Text::Report("selection", false));let done = progress.done.load(std::sync::atomic::Ordering::Relaxed);let total = progress.total.load(std::sync::atomic::Ordering::Relaxed).max(1);let mb = |b: u64| format!("{:.1}", b as f64 / 1_048_576.0);diff --git a/crates/ui-egui/src/update/install.rs b/crates/ui-egui/src/update/install.rsindex b954475e98..4eee689168 100644--- a/crates/ui-egui/src/update/install.rs+++ b/crates/ui-egui/src/update/install.rs@@ -20,8 +20,8 @@use std::io::{Read, Write};use std::path::{Path, PathBuf};-use std::sync::Arc;use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};+use std::sync::{Arc, Mutex};use sha2::{Digest, Sha256};@@ -145,16 +145,36 @@ pub struct Progress {pub done: AtomicU64,pub total: AtomicU64,pub cancel: AtomicBool,+ /// Final release and whether the refresh failed; absent while checking.+ selected: Mutex<Option<(Release, bool)>>,+}++impl Progress {+ pub fn selection(&self) -> Option<(Release, bool)> {+ self.selected.lock().unwrap_or_else(|e| e.into_inner()).clone()+ }++ pub fn message(&self) -> String {+ let selected = self.selected.lock().unwrap_or_else(|e| e.into_inner());+ match selected.as_ref() {+ None => crate::i18n::tr("update.refresh_checking").to_string(),+ Some((release, fallback)) => {+ crate::i18n::format(if *fallback { "update.refresh_fallback" } else { "update.refresh_selected" }, &[("version", release.version())])+ }+ }+ }}/// What the update needs from the host.pub struct Net {pub get: super::HttpGet,pub download: HttpDownload,+ pub feed: Option<PathBuf>,}-/// Download, verify and apply `release` for `method`. Runs on a background thread. `staging` is-/// a folder for downloads that aren't written next to their target (the `.msi`, the `.dmg`).+/// Refresh the feed, then download, verify and apply the newest release for `method`, falling+/// back to `release` when the check fails. Runs on a background thread. `staging` holds downloads+/// that are not written next to their target (the `.msi`, the `.dmg`).pub fn run(release: &Release,kind: &InstallKind,@@ -164,6 +184,17 @@ pub fn run(staging: &Path,progress: &Progress,) -> Result<Outcome, String> {+ // The release shown may be stale by now: install the newest one the feed names, or the one+ // shown when the feed can't be read.+ let (release, fallback) = match super::fetch_latest(net.feed.as_deref(), Some(&net.get)) {+ Ok(latest) if super::is_newer(&latest.tag, &release.tag) => (latest, false),+ Ok(_) => (release.clone(), false),+ Err(_) => (release.clone(), true),+ };+ *progress.selected.lock().unwrap_or_else(|e| e.into_inner()) = Some((release.clone(), fallback));+ if progress.cancel.load(Ordering::Relaxed) {+ return Err("cancelled".into());+ }let asset = release.asset_for(kind, arch).ok_or_else(|| format!("this release has no package for a {} on {arch}", kind.label()))?;if asset.size > MAX_PACKAGE {return Err(format!("{} is too large ({} bytes)", asset.name, asset.size));diff --git a/crates/ui-egui/src/update/install_tests.rs b/crates/ui-egui/src/update/install_tests.rsindex bacef38c48..2fa03c85c5 100644--- a/crates/ui-egui/src/update/install_tests.rs+++ b/crates/ui-egui/src/update/install_tests.rs@@ -87,6 +87,7 @@ fn net(files: Vec<(String, Vec<u8>)>) -> Net {let find = move |files: &[(String, Vec<u8>)], url: &str| files.iter().find(|(n, _)| url == format!("{BASE}{n}")).map(|(_, b)| b.clone());let find2 = find;Net {+ feed: None,get: Arc::new(move |url: &str| find(&files, url).ok_or_else(|| FetchError::Failed(format!("404 {url}")))),download: Arc::new(move |url: &str, to: &Path, progress: &dyn Fn(u64, Option<u64>) -> bool| {let body = find2(&f2, url).ok_or_else(|| FetchError::Failed(format!("404 {url}")))?;@@ -246,3 +247,66 @@ fn an_updated_appimage_takes_the_release_file_name() {assert_eq!(std::fs::read_dir(&dir).unwrap().count(), 1, "nothing else is left behind");let _ = std::fs::remove_dir_all(&dir);}++#[test]+fn installation_refreshes_the_release_and_verifies_the_final_package() {+ let dir = scratch("refresh");+ let target = dir.join("SolidCraft.AppImage");+ let name = "solidcraft-linux-x86_64.AppImage";+ let shown = release_with(&[(name, 3), (SUMS, 100)]);+ let base = "https://github.com/tangency-labs/solidcraft/releases/download/v10.0.0/";+ let feed = serde_json::json!({+ "tag_name": "v10.0.0",+ "assets": [+ {"name": name, "browser_download_url": format!("{base}{name}"), "size": 3},+ {"name": SUMS, "browser_download_url": format!("{base}{SUMS}")}+ ]+ })+ .to_string()+ .into_bytes();+ for (case, answer, corrupt, expected, fallback) in [+ ("newest", Ok(feed.clone()), false, "10.0.0", false),+ ("corrupt newest", Ok(feed), true, "10.0.0", false),+ ("offline", Err(FetchError::Failed("offline".into())), false, "9.9.9", true),+ ("rate limited", Err(FetchError::RateLimited { retry_after_s: 60 }), false, "9.9.9", true),+ ("oversized", Ok(vec![b' '; super::MAX_RELEASE_BYTES + 1]), false, "9.9.9", true),+ ("older", Ok(br#"{"tag_name":"v9.9.8"}"#.to_vec()), false, "9.9.9", false),+ ] {+ std::fs::write(&target, b"old").unwrap();+ let chosen_base = if expected == "10.0.0" { base } else { BASE };+ let n = Net {+ feed: None,+ get: Arc::new(move |url| {+ if url == super::LATEST_API {+ return answer.clone();+ }+ assert_eq!(url, format!("{chosen_base}{SUMS}"), "checksums from the chosen release");+ Ok(format!("{} {name}\n", hex(if corrupt { b"bad" } else { b"new" })).into_bytes())+ }),+ download: Arc::new(move |url, to, report| {+ assert_eq!(url, format!("{chosen_base}{name}"), "package from the chosen release");+ std::fs::write(to, b"new").unwrap();+ assert!(report(3, Some(3)));+ Ok(())+ }),+ };+ let p = Progress::default();+ let result = run(&shown, &InstallKind::AppImage(target.clone()), &Method::AppImage(target.clone()), "x86_64", &n, &dir, &p);+ let (selected, used_fallback) = p.selection().unwrap();+ assert_eq!(selected.version(), expected, "{case}");+ assert_eq!(used_fallback, fallback, "{case}");+ assert_eq!(+ p.message(),+ crate::i18n::format(if fallback { "update.refresh_fallback" } else { "update.refresh_selected" }, &[("version", expected)]),+ "{case}"+ );+ if corrupt {+ assert!(result.unwrap_err().contains("doesn't match"));+ assert_eq!(std::fs::read(&target).unwrap(), b"old");+ } else {+ assert_eq!(result.unwrap(), Outcome::Restart(target.clone()), "{case}");+ assert_eq!(std::fs::read(&target).unwrap(), b"new");+ }+ }+ let _ = std::fs::remove_dir_all(dir);+}diff --git a/crates/ui-egui/src/update/tests.rs b/crates/ui-egui/src/update/tests.rsindex dc250a1bed..e192fdaeea 100644--- a/crates/ui-egui/src/update/tests.rs+++ b/crates/ui-egui/src/update/tests.rs@@ -686,3 +686,67 @@ fn an_unmanaged_install_updates_itself_as_before() {assert!(h.widget("Download").is_some());assert!(h.widget("Update available: update SolidCraft in ArtCraft Launcher").is_none());}++#[test]+fn periodic_checks_refresh_the_offered_label() {+ let dir = scratch();+ let (feed, first) = next_release_feed(&dir.0);+ let mut h = crate::scenario::Harness::new();+ h.app.updater.feed = Some(feed.clone());+ h.frame();+ wait_for_check(&mut h);+ h.frames(2);+ assert!(h.widget(&format!("Update to {first}")).is_some());+ h.app.updater.installed = Some(Ok(install::Outcome::Restart(dir.0.join("SolidCraft.AppImage"))));+ let v = parse_version(&first).unwrap();+ let next = format!("{}.{}.0", v.major, v.minor + 1);+ std::fs::write(feed, json!({"tag_name": format!("v{next}")}).to_string()).unwrap();+ h.app.preferences.update.next_check = 0.0;+ h.frame();+ wait_for_check(&mut h);+ h.frames(2);+ assert!(h.widget(&format!("Update to {next}")).is_some());+ assert!(h.widget(&format!("Update to {first}")).is_none());+}++#[test]+fn install_selection_refreshes_the_button_and_progress_before_completion() {+ let dir = scratch();+ let target = dir.0.join("SolidCraft.AppImage");+ let name = asset_name(&InstallKind::AppImage(target.clone()), std::env::consts::ARCH, "999.1.0").unwrap();+ let mut h = crate::scenario::Harness::new();+ h.app.preferences.check_updates = false;+ let mut shown = release();+ shown.tag = "v999.0.0".into();+ h.app.updater.release = Some(shown);+ h.app.updater.kind = Some(InstallKind::AppImage(target));+ h.app.updater.open = true;+ h.app.services.http_get = Some(Arc::new(move |url| {+ if url == LATEST_API {+ return Ok(json!({"tag_name":"v999.1.0", "assets":[+ {"name": name, "browser_download_url":format!("https://github.com/tangency-labs/solidcraft/releases/download/v999.1.0/{name}")},+ {"name": install::SUMS, "browser_download_url":"https://github.com/tangency-labs/solidcraft/releases/download/v999.1.0/SHA256SUMS.txt"}+ ]}).to_string().into_bytes());+ }+ Ok(format!("{} {name}\n", "a".repeat(64)).into_bytes())+ }));+ let (tx, rx) = std::sync::mpsc::channel();+ let rx = std::sync::Mutex::new(rx);+ h.app.services.http_download = Some(Arc::new(move |_, _, _| {+ rx.lock().unwrap().recv().unwrap();+ Err(FetchError::Failed("download stopped".into()))+ }));+ start_install(&mut h.app, &egui::Context::default());+ for _ in 0..500 {+ poll_install(&mut h.app);+ if h.app.updater.release.as_ref().unwrap().version() == "999.1.0" {+ break;+ }+ std::thread::sleep(std::time::Duration::from_millis(2));+ }+ h.frames(2);+ assert!(h.widget("Update to 999.1.0").is_some());+ assert!(h.widget("Updating to 999.1.0.").is_some());+ assert!(h.app.updater.installed.is_none());+ tx.send(()).unwrap();+}