diff --git a/crates/clash-verge-i18n/locales/ar.yml b/crates/clash-verge-i18n/locales/ar.yml index 523f49c55..4476f4da3 100644 --- a/crates/clash-verge-i18n/locales/ar.yml +++ b/crates/clash-verge-i18n/locales/ar.yml @@ -29,11 +29,6 @@ notifications: appQuit: title: على وشك الخروج body: Clash Verge على وشك الخروج. - updateReady: - title: Clash Verge Update - body: A new version (v{version}) has been downloaded and is ready to install. - installNow: Install Now - later: Later service: adminInstallPrompt: يتطلب تثبيت خدمة Clash Verge صلاحيات المسؤول. adminUninstallPrompt: يتطلب إلغاء تثبيت خدمة Clash Verge صلاحيات المسؤول. diff --git a/crates/clash-verge-i18n/locales/de.yml b/crates/clash-verge-i18n/locales/de.yml index d8accd74b..580e7ddd7 100644 --- a/crates/clash-verge-i18n/locales/de.yml +++ b/crates/clash-verge-i18n/locales/de.yml @@ -29,11 +29,6 @@ notifications: appQuit: title: Beenden steht bevor body: Clash Verge wird gleich beendet. - updateReady: - title: Clash-Verge-Update - body: Eine neue Version (v{version}) wurde heruntergeladen und kann installiert werden. - installNow: Jetzt installieren - later: Später service: adminInstallPrompt: Für die Installation des Clash-Verge-Dienstes sind Administratorrechte erforderlich. adminUninstallPrompt: Für die Deinstallation des Clash-Verge-Dienstes sind Administratorrechte erforderlich. diff --git a/crates/clash-verge-i18n/locales/en.yml b/crates/clash-verge-i18n/locales/en.yml index d1b144b94..ecad0ddf3 100644 --- a/crates/clash-verge-i18n/locales/en.yml +++ b/crates/clash-verge-i18n/locales/en.yml @@ -29,11 +29,6 @@ notifications: appQuit: title: About to Exit body: Clash Verge is about to exit. - updateReady: - title: Clash Verge Update - body: A new version (v{version}) has been downloaded and is ready to install. - installNow: Install Now - later: Later service: adminInstallPrompt: Installing the Clash Verge service requires administrator privileges. adminUninstallPrompt: Uninstalling the Clash Verge service requires administrator privileges. diff --git a/crates/clash-verge-i18n/locales/es.yml b/crates/clash-verge-i18n/locales/es.yml index 119d630d7..76ecd7e96 100644 --- a/crates/clash-verge-i18n/locales/es.yml +++ b/crates/clash-verge-i18n/locales/es.yml @@ -29,11 +29,6 @@ notifications: appQuit: title: A punto de salir body: Clash Verge está a punto de salir. - updateReady: - title: Clash Verge Update - body: A new version (v{version}) has been downloaded and is ready to install. - installNow: Install Now - later: Later service: adminInstallPrompt: Instalar el servicio de Clash Verge requiere privilegios de administrador. adminUninstallPrompt: Desinstalar el servicio de Clash Verge requiere privilegios de administrador. diff --git a/crates/clash-verge-i18n/locales/fa.yml b/crates/clash-verge-i18n/locales/fa.yml index e5270cebd..b21404682 100644 --- a/crates/clash-verge-i18n/locales/fa.yml +++ b/crates/clash-verge-i18n/locales/fa.yml @@ -29,11 +29,6 @@ notifications: appQuit: title: در آستانه خروج body: Clash Verge در آستانه خروج است. - updateReady: - title: Clash Verge Update - body: A new version (v{version}) has been downloaded and is ready to install. - installNow: Install Now - later: Later service: adminInstallPrompt: نصب سرویس Clash Verge به دسترسی مدیر نیاز دارد. adminUninstallPrompt: حذف سرویس Clash Verge به دسترسی مدیر نیاز دارد. diff --git a/crates/clash-verge-i18n/locales/id.yml b/crates/clash-verge-i18n/locales/id.yml index 316b3e523..cf2750a26 100644 --- a/crates/clash-verge-i18n/locales/id.yml +++ b/crates/clash-verge-i18n/locales/id.yml @@ -29,11 +29,6 @@ notifications: appQuit: title: Akan Keluar body: Clash Verge akan keluar. - updateReady: - title: Clash Verge Update - body: A new version (v{version}) has been downloaded and is ready to install. - installNow: Install Now - later: Later service: adminInstallPrompt: Menginstal layanan Clash Verge memerlukan hak administrator. adminUninstallPrompt: Menghapus instalasi layanan Clash Verge memerlukan hak administrator. diff --git a/crates/clash-verge-i18n/locales/jp.yml b/crates/clash-verge-i18n/locales/jp.yml index 9817405e6..2ca38403c 100644 --- a/crates/clash-verge-i18n/locales/jp.yml +++ b/crates/clash-verge-i18n/locales/jp.yml @@ -29,11 +29,6 @@ notifications: appQuit: title: 終了間近 body: Clash Verge はまもなく終了します。 - updateReady: - title: Clash Verge Update - body: A new version (v{version}) has been downloaded and is ready to install. - installNow: Install Now - later: Later service: adminInstallPrompt: Clash Verge サービスのインストールには管理者権限が必要です。 adminUninstallPrompt: Clash Verge サービスのアンインストールには管理者権限が必要です。 diff --git a/crates/clash-verge-i18n/locales/ko.yml b/crates/clash-verge-i18n/locales/ko.yml index 241d0d327..900d7d5ad 100644 --- a/crates/clash-verge-i18n/locales/ko.yml +++ b/crates/clash-verge-i18n/locales/ko.yml @@ -29,11 +29,6 @@ notifications: appQuit: title: 곧 종료 body: Clash Verge가 곧 종료됩니다. - updateReady: - title: Clash Verge Update - body: A new version (v{version}) has been downloaded and is ready to install. - installNow: Install Now - later: Later service: adminInstallPrompt: Clash Verge 서비스 설치에는 관리자 권한이 필요합니다. adminUninstallPrompt: Clash Verge 서비스 제거에는 관리자 권한이 필요합니다. diff --git a/crates/clash-verge-i18n/locales/pt.yml b/crates/clash-verge-i18n/locales/pt.yml index 2373529ee..8daacfafd 100644 --- a/crates/clash-verge-i18n/locales/pt.yml +++ b/crates/clash-verge-i18n/locales/pt.yml @@ -29,11 +29,6 @@ notifications: appQuit: title: Prestes a sair body: O Clash Verge está prestes a sair. - updateReady: - title: Atualização do Clash Verge - body: Uma nova versão (v{version}) foi baixada e está pronta para instalar. - installNow: Instalar agora - later: Depois service: adminInstallPrompt: A instalação do serviço do Clash Verge requer privilégios de administrador. adminUninstallPrompt: A desinstalação do serviço do Clash Verge requer privilégios de administrador. diff --git a/crates/clash-verge-i18n/locales/ru.yml b/crates/clash-verge-i18n/locales/ru.yml index 985b9d1e6..38b476763 100644 --- a/crates/clash-verge-i18n/locales/ru.yml +++ b/crates/clash-verge-i18n/locales/ru.yml @@ -29,11 +29,6 @@ notifications: appQuit: title: Скорый выход body: Clash Verge скоро завершит работу. - updateReady: - title: Обновление Clash Verge - body: Новая версия (v{version}) скачана и готова к установке. - installNow: Установить сейчас - later: Позже service: adminInstallPrompt: Для установки службы Clash Verge требуются права администратора. adminUninstallPrompt: Для удаления службы Clash Verge требуются права администратора. diff --git a/crates/clash-verge-i18n/locales/tr.yml b/crates/clash-verge-i18n/locales/tr.yml index 0d0f0c945..191267edc 100644 --- a/crates/clash-verge-i18n/locales/tr.yml +++ b/crates/clash-verge-i18n/locales/tr.yml @@ -29,11 +29,6 @@ notifications: appQuit: title: Çıkış Yapılmak Üzere body: Clash Verge kapanmak üzere. - updateReady: - title: Clash Verge Güncellemesi - body: Yeni bir sürüm (v{version}) indirildi ve kurulmaya hazır. - installNow: Şimdi Kur - later: Daha Sonra service: adminInstallPrompt: Clash Verge hizmetini kurmak için yönetici ayrıcalıkları gerekir. adminUninstallPrompt: Clash Verge hizmetini kaldırmak için yönetici ayrıcalıkları gerekir. diff --git a/crates/clash-verge-i18n/locales/tt.yml b/crates/clash-verge-i18n/locales/tt.yml index c136061ae..1a9e4580b 100644 --- a/crates/clash-verge-i18n/locales/tt.yml +++ b/crates/clash-verge-i18n/locales/tt.yml @@ -29,11 +29,6 @@ notifications: appQuit: title: Чыгар алдыннан body: Clash Verge чыгарга җыена. - updateReady: - title: Clash Verge Update - body: A new version (v{version}) has been downloaded and is ready to install. - installNow: Install Now - later: Later service: adminInstallPrompt: Clash Verge хезмәтен урнаштыру өчен администратор хокуклары кирәк. adminUninstallPrompt: Clash Verge хезмәтен бетерү өчен администратор хокуклары кирәк. diff --git a/crates/clash-verge-i18n/locales/zh.yml b/crates/clash-verge-i18n/locales/zh.yml index d87c1e2f0..020d8640d 100644 --- a/crates/clash-verge-i18n/locales/zh.yml +++ b/crates/clash-verge-i18n/locales/zh.yml @@ -29,11 +29,6 @@ notifications: appQuit: title: 即将退出 body: Clash Verge 即将退出。 - updateReady: - title: Clash Verge 更新 - body: 新版本 (v{version}) 已下载完成,是否立即安装? - installNow: 立即安装 - later: 稍后 service: adminInstallPrompt: 安装 Clash Verge 服务需要管理员权限 adminUninstallPrompt: 卸载 Clash Verge 服务需要管理员权限 diff --git a/crates/clash-verge-i18n/locales/zhtw.yml b/crates/clash-verge-i18n/locales/zhtw.yml index b6baa3adb..9f7ac03b8 100644 --- a/crates/clash-verge-i18n/locales/zhtw.yml +++ b/crates/clash-verge-i18n/locales/zhtw.yml @@ -29,11 +29,6 @@ notifications: appQuit: title: 即將退出 body: Clash Verge 即將退出。 - updateReady: - title: Clash Verge 更新 - body: 新版本(v{version})已下載完成,是否立即安裝? - installNow: 立即安裝 - later: 稍後 service: adminInstallPrompt: 安裝 Clash Verge 服務需要管理員權限 adminUninstallPrompt: 解除安裝 Clash Verge 服務需要管理員權限 diff --git a/src-tauri/src/core/updater.rs b/src-tauri/src/core/updater.rs index d6e902772..3d4acec80 100644 --- a/src-tauri/src/core/updater.rs +++ b/src-tauri/src/core/updater.rs @@ -1,21 +1,20 @@ use crate::{config::Config, singleton, utils::dirs}; use anyhow::{Context as _, Result}; -use chrono::Utc; use clash_verge_logging::{Type, logging}; use parking_lot::Mutex; use serde::{Deserialize, Serialize}; use std::{ path::PathBuf, - sync::atomic::{AtomicBool, AtomicU64, Ordering}, + sync::atomic::{AtomicU64, Ordering}, time::Duration, }; use tauri_plugin_updater::{Update, UpdaterExt as _}; use tokio_util::sync::CancellationToken; pub struct SilentUpdater { - update_ready: AtomicBool, manual_cancel: Mutex>, background_cancel: Mutex>, + download_lock: tokio::sync::Mutex<()>, } #[derive(Serialize, specta::Type)] @@ -31,21 +30,16 @@ singleton!(SilentUpdater, SILENT_UPDATER); impl SilentUpdater { const fn new() -> Self { Self { - update_ready: AtomicBool::new(false), manual_cancel: Mutex::new(None), background_cancel: Mutex::new(None), + download_lock: tokio::sync::Mutex::const_new(()), } } - - pub fn is_update_ready(&self) -> bool { - self.update_ready.load(Ordering::Acquire) - } } #[derive(Serialize, Deserialize)] struct UpdateCacheMeta { version: String, - downloaded_at: String, } impl SilentUpdater { @@ -53,36 +47,45 @@ impl SilentUpdater { Ok(dirs::app_home_dir()?.join("update_cache")) } - fn write_cache(bytes: &[u8], version: &str) -> Result<()> { + /// Writes the payload through a temp file so a crash leaves no partial `pending_update.bin`; + /// installer-sized IO stays off the async runtime. + async fn write_cache(bytes: Vec, version: &str) -> Result<()> { let cache_dir = Self::cache_dir()?; - std::fs::create_dir_all(&cache_dir) - .with_context(|| format!("failed to create update cache directory {}", cache_dir.display()))?; + let version = version.to_owned(); + tokio::task::spawn_blocking(move || -> Result<()> { + std::fs::create_dir_all(&cache_dir) + .with_context(|| format!("failed to create update cache directory {}", cache_dir.display()))?; - let bin_path = cache_dir.join("pending_update.bin"); - std::fs::write(&bin_path, bytes) - .with_context(|| format!("failed to write update cache {}", bin_path.display()))?; + let bin_path = cache_dir.join("pending_update.bin"); + let tmp_path = cache_dir.join("pending_update.bin.tmp"); + std::fs::write(&tmp_path, &bytes) + .with_context(|| format!("failed to write update cache {}", tmp_path.display()))?; + std::fs::rename(&tmp_path, &bin_path) + .with_context(|| format!("failed to rename update cache {}", bin_path.display()))?; - let meta = UpdateCacheMeta { - version: version.to_string(), - downloaded_at: Utc::now().to_rfc3339(), - }; - let meta_path = cache_dir.join("pending_update.json"); - std::fs::write(&meta_path, serde_json::to_string_pretty(&meta)?) - .with_context(|| format!("failed to write update metadata {}", meta_path.display()))?; + let meta = UpdateCacheMeta { version }; + let meta_path = cache_dir.join("pending_update.json"); + std::fs::write(&meta_path, serde_json::to_string_pretty(&meta)?) + .with_context(|| format!("failed to write update metadata {}", meta_path.display()))?; - logging!( - info, - Type::System, - "Update cache written: version={}, size={} bytes", - version, - bytes.len() - ); - Ok(()) + logging!( + info, + Type::System, + "Update cache written: version={}, size={} bytes", + meta.version, + bytes.len() + ); + Ok(()) + }) + .await? } - fn read_cache_bytes() -> Result> { + async fn read_cache_bytes() -> Result> { let bin_path = Self::cache_dir()?.join("pending_update.bin"); - std::fs::read(&bin_path).with_context(|| format!("failed to read update cache {}", bin_path.display())) + tokio::task::spawn_blocking(move || { + std::fs::read(&bin_path).with_context(|| format!("failed to read update cache {}", bin_path.display())) + }) + .await? } fn read_cache_meta() -> Result { @@ -91,28 +94,31 @@ impl SilentUpdater { Ok(serde_json::from_str(&content)?) } - fn delete_cache() { + async fn delete_cache() { if let Ok(cache_dir) = Self::cache_dir() && cache_dir.exists() { - if let Err(e) = std::fs::remove_dir_all(&cache_dir) { - logging!( - warn, - Type::System, - "Failed to delete update cache {}: {e}", - cache_dir.display() - ); - } else { - logging!(info, Type::System, "Update cache deleted"); + let display = cache_dir.display().to_string(); + match tokio::task::spawn_blocking(move || std::fs::remove_dir_all(&cache_dir)).await { + Ok(Ok(())) => logging!(info, Type::System, "Update cache deleted"), + Ok(Err(e)) => logging!(warn, Type::System, "Failed to delete update cache {display}: {e}"), + Err(e) => logging!(warn, Type::System, "Failed to delete update cache {display}: {e}"), } } } /// Returns the cached installer for `update`, deleting a cache that does not match it. - fn verified_cache(update: &Update) -> Option> { - let meta = Self::read_cache_meta().ok()?; + async fn verified_cache(update: &Update) -> Option> { + let meta = match Self::read_cache_meta() { + Ok(meta) => meta, + // A bin without its meta comes from an interrupted write. + Err(_) => { + Self::delete_cache().await; + return None; + } + }; let bytes = if meta.version == update.version { - Self::read_cache_bytes().and_then(|bytes| { + Self::read_cache_bytes().await.and_then(|bytes| { update.verify(&bytes)?; Ok(bytes) }) @@ -128,7 +134,7 @@ impl SilentUpdater { "Update cache v{} is unusable: {e:#}, cleaning up", meta.version ); - Self::delete_cache(); + Self::delete_cache().await; None } } @@ -142,35 +148,6 @@ pub fn is_build_to_stable(current: &str, remote: &str) -> bool { !build.is_empty() && !base.contains('-') && base == remote.trim_start_matches('v') } -/// Compares numeric version components after stripping version suffixes. -fn version_lte(a: &str, b: &str) -> bool { - let parse = |v: &str| -> Vec { - v.trim_start_matches('v') - .split(['-', '+']) - .next() - .unwrap_or("0") - .split('.') - .filter_map(|part| part.parse::().ok()) - .collect() - }; - - let a_parts = parse(a); - let b_parts = parse(b); - let len = a_parts.len().max(b_parts.len()); - - for i in 0..len { - let av = a_parts.get(i).copied().unwrap_or(0); - let bv = b_parts.get(i).copied().unwrap_or(0); - if av < bv { - return true; - } - if av > bv { - return false; - } - } - true // equal -} - /// Maps UI language to one of the three NSIS translations, defaulting to English. #[cfg(target_os = "windows")] fn nsis_language_id(app_language: &str) -> &'static str { @@ -302,7 +279,7 @@ impl SilentUpdater { /// re-trigger. A timeout abandons the await, not the detached install task; a successful /// Windows install exits the process inside the plugin (#2558). async fn install(update: Update, bytes: Vec) -> Result<()> { - Self::delete_cache(); + Self::delete_cache().await; let install = tokio::task::spawn_blocking(move || update.install(&bytes)); match tokio::time::timeout(INSTALL_TIMEOUT, install).await { Ok(result) => Ok(result??), @@ -312,91 +289,6 @@ impl SilentUpdater { } } - /// Installs a newer cached update before normal startup, if the user confirms. - pub async fn try_install_on_startup(&self, app_handle: &tauri::AppHandle) -> bool { - if !Config::verge().await.latest_arc().auto_check_update.unwrap_or(true) { - Self::delete_cache(); - return false; - } - - let current_version = env!("CARGO_PKG_VERSION"); - - let meta = match Self::read_cache_meta() { - Ok(meta) => meta, - Err(_) => return false, // No cache, nothing to do - }; - - let cached_version = &meta.version; - - if !is_build_to_stable(current_version, cached_version) && version_lte(cached_version, current_version) { - logging!( - info, - Type::System, - "Update cache version ({}) <= current ({}), cleaning up", - cached_version, - current_version - ); - Self::delete_cache(); - return false; - } - - logging!( - info, - Type::System, - "Update cache version ({}) > current ({}), asking user to install", - cached_version, - current_version - ); - - // Preserve the cache when skipped so the next launch asks again. - if !Self::ask_user_to_install(app_handle, cached_version).await { - logging!(info, Type::System, "User skipped update install, starting normally"); - return false; - } - - let update = match Self::check(app_handle).await { - Ok(Some(u)) => u, - Ok(None) => { - logging!( - info, - Type::System, - "No update available from server, cache may be stale, cleaning up" - ); - Self::delete_cache(); - return false; - } - Err(e) => { - logging!( - warn, - Type::System, - "Failed to check for update at startup: {e:#}, will retry next launch" - ); - return false; // Keep cache for next attempt - } - }; - - let Some(bytes) = Self::verified_cache(&update) else { - return false; - }; - - let version = update.version.clone(); - logging!(info, Type::System, "Installing cached update v{version} at startup..."); - - Self::show_update_splash(app_handle, &version); - - match Self::install(update, bytes).await { - Ok(()) => { - logging!(info, Type::System, "Update v{version} installed at startup"); - true - } - Err(e) => { - logging!(warn, Type::System, "Startup install failed: {e:#}"); - Self::close_update_splash(app_handle); - false - } - } - } - /// Installs `version` for the update dialog, reusing the cache when it holds that version; /// A changed offer must be confirmed again before downloading or installing it. pub async fn install_update( @@ -406,9 +298,13 @@ impl SilentUpdater { on_event: impl Fn(DownloadEvent) + Sync, ) -> Result { let cancel = CancellationToken::new(); - *self.manual_cancel.lock() = Some(cancel.clone()); + { + let mut slot = self.manual_cancel.lock(); + anyhow::ensure!(slot.is_none(), "an update install is already in progress"); + *slot = Some(cancel.clone()); + } let prepared = tokio::select! { - prepared = Self::prepare_install(app_handle, version, &on_event) => Some(prepared), + prepared = self.prepare_install(app_handle, version, &on_event) => Some(prepared), () = cancel.cancelled() => None, }; // `cancel_download` cancels under the lock, so once the token is taken back its state is @@ -429,6 +325,7 @@ impl SilentUpdater { } async fn prepare_install( + &self, app_handle: &tauri::AppHandle, version: &str, on_event: &(impl Fn(DownloadEvent) + Sync), @@ -439,7 +336,8 @@ impl SilentUpdater { else { return Ok(None); }; - let bytes = match Self::verified_cache(&update) { + let _download_guard = self.download_lock.lock().await; + let bytes = match Self::verified_cache(&update).await { Some(bytes) => bytes, None => download(&update, on_event).await?, }; @@ -454,120 +352,12 @@ impl SilentUpdater { } /// Drops the downloaded update and aborts a background download in flight. - pub fn discard_pending(&self) { + pub async fn discard_pending(&self) { let cancel = self.background_cancel.lock().take(); if let Some(cancel) = cancel { cancel.cancel(); } - self.update_ready.store(false, Ordering::Release); - Self::delete_cache(); - } -} - -impl SilentUpdater { - async fn ask_user_to_install(app_handle: &tauri::AppHandle, version: &str) -> bool { - use tauri_plugin_dialog::{DialogExt as _, MessageDialogButtons, MessageDialogKind}; - - let title = clash_verge_i18n::t!("notifications.updateReady.title"); - let body = clash_verge_i18n::t!("notifications.updateReady.body").replace("{version}", version); - let install_now = clash_verge_i18n::t!("notifications.updateReady.installNow").into_owned(); - let later = clash_verge_i18n::t!("notifications.updateReady.later").into_owned(); - - let (tx, rx) = tokio::sync::oneshot::channel(); - - app_handle - .dialog() - .message(body) - .title(title) - .buttons(MessageDialogButtons::OkCancelCustom(install_now, later)) - .kind(MessageDialogKind::Info) - .show(move |confirmed| { - let _ = tx.send(confirmed); - }); - - rx.await.unwrap_or(false) - } -} - -impl SilentUpdater { - /// Uses injected HTML so the splash has no bundled-file dependency. - fn show_update_splash(app_handle: &tauri::AppHandle, version: &str) { - use tauri::{WebviewUrl, WebviewWindowBuilder}; - - let window = match WebviewWindowBuilder::new(app_handle, "update-splash", WebviewUrl::App("index.html".into())) - .title("Clash Verge - Updating") - .inner_size(300.0, 180.0) - .resizable(false) - .maximizable(false) - .minimizable(false) - .closable(false) - .decorations(false) - .center() - .always_on_top(true) - .visible(true) - .build() - { - Ok(w) => w, - Err(e) => { - logging!(warn, Type::System, "Failed to create update splash: {e}"); - return; - } - }; - - let js = format!( - r#" - document.documentElement.innerHTML = ` - - - - - - -
Installing Update...
-
v{version}
-
- `; - "# - ); - - // The new webview may not accept evaluation immediately. - std::thread::spawn(move || { - use crate::utils::retry::{RetryError, RetryPolicy, retry_sync}; - let _ = retry_sync( - RetryPolicy::fixed(std::num::NonZeroUsize::MIN.saturating_add(9), std::time::Duration::ZERO), - |index| { - std::thread::sleep(std::time::Duration::from_millis(100 * (index as u64 + 1))); - window.eval(&js).map_err(RetryError::Retry) - }, - ); - }); - - logging!(info, Type::System, "Update splash window shown"); - } - - fn close_update_splash(app_handle: &tauri::AppHandle) { - use tauri::Manager as _; - if let Some(window) = app_handle.get_webview_window("update-splash") { - let _ = window.close(); - logging!(info, Type::System, "Update splash window closed"); - } + Self::delete_cache().await; } } @@ -582,11 +372,6 @@ impl SilentUpdater { return Ok(()); } - if self.is_update_ready() { - logging!(debug, Type::System, "Silent update skipped: update already pending"); - return Ok(()); - } - logging!(info, Type::System, "Silent updater: checking for updates..."); let updater = app_handle.updater()?; @@ -605,7 +390,13 @@ impl SilentUpdater { let version = update.version.as_str(); logging!(info, Type::System, "Silent updater: update available: v{version}"); - if Self::verified_cache(&update).is_some() { + let download_guard = self.download_lock.lock().await; + // A discard that arrived while waiting for the lock must not start a doomed download. + if cancel.is_cancelled() { + return Ok(()); + } + + if Self::verified_cache(&update).await.is_some() { logging!(info, Type::System, "Silent updater: v{version} already cached"); } else { logging!(info, Type::System, "Silent updater: downloading v{version}..."); @@ -619,27 +410,30 @@ impl SilentUpdater { }; let bytes = bytes?; logging!(info, Type::System, "Silent updater: download complete"); - Self::write_cache(&bytes, version)?; + Self::write_cache(bytes, version).await?; } + drop(download_guard); - // Serialized with `discard_pending` in the verge patch, which holds the same lock. - let _config_write = Config::lock_config_write().await; - if cancel.is_cancelled() || !Config::verge().await.latest_arc().auto_check_update.unwrap_or(true) { + // Serialized with `discard_pending` in the verge patch, which holds the same lock; + // the deletion itself is idempotent, so it runs after the lock. + let discard = { + let _config_write = Config::lock_config_write().await; + cancel.is_cancelled() || !Config::verge().await.latest_arc().auto_check_update.unwrap_or(true) + }; + if discard { logging!( info, Type::System, "Silent updater: auto check was disabled, discarding v{version}" ); - Self::delete_cache(); + Self::delete_cache().await; return Ok(()); } - self.update_ready.store(true, Ordering::Release); - logging!( info, Type::System, - "Silent updater: v{version} ready for startup install on next launch" + "Silent updater: v{version} ready to install from the update dialog" ); Ok(()) } @@ -659,3 +453,16 @@ impl SilentUpdater { } } } + +#[cfg(test)] +mod tests { + use super::is_build_to_stable; + + #[test] + fn is_build_to_stable_matches_build_metadata_to_the_same_base() { + assert!(is_build_to_stable("2.4.3+5", "2.4.3")); + assert!(!is_build_to_stable("2.4.3+5", "2.4.4")); + assert!(!is_build_to_stable("2.4.3", "2.4.3")); + assert!(!is_build_to_stable("2.4.3-beta+5", "2.4.3")); + } +} diff --git a/src-tauri/src/feat/executor.rs b/src-tauri/src/feat/executor.rs index 71f8820da..fbbf50a74 100644 --- a/src-tauri/src/feat/executor.rs +++ b/src-tauri/src/feat/executor.rs @@ -164,7 +164,7 @@ pub(super) async fn apply(config_write: &MutexGuard<'_, ()>, patch: Patch<'_>, e match patch { Patch::Verge { patch, .. } => { if patch.auto_check_update == Some(false) { - SilentUpdater::global().discard_pending(); + SilentUpdater::global().discard_pending().await; } if effects.contains(&Effect::ClashConfig) { announce(Refresh::Clash); diff --git a/src-tauri/src/utils/resolve/mod.rs b/src-tauri/src/utils/resolve/mod.rs index fa408f2af..822a0b24b 100644 --- a/src-tauri/src/utils/resolve/mod.rs +++ b/src-tauri/src/utils/resolve/mod.rs @@ -80,6 +80,8 @@ async fn resolve_setup() { init_core_manager().await; }); + init_silent_updater(); + let _ = futures::join!( core_init, init_tray(), @@ -87,7 +89,6 @@ async fn resolve_setup() { init_hotkey(), init_auto_lightweight_boot(), init_auto_backup(), - init_silent_updater(), ); Handle::refresh_clash(); @@ -152,20 +153,13 @@ async fn init_auto_backup() { logging_error!(Type::Setup, AutoBackupManager::global().init().await); } -async fn init_silent_updater() { +fn init_silent_updater() { use crate::core::SilentUpdater; use crate::core::handle::Handle; logging!(debug, Type::Setup, "Initializing silent updater..."); let app_handle = Handle::app_handle(); - - // Install cached updates before starting background checks. - if SilentUpdater::global().try_install_on_startup(app_handle).await { - logging!(info, Type::Setup, "Update installed at startup, restarting..."); - feat::restart_app().await; - } - let app_handle = app_handle.clone(); tokio::spawn(async move { SilentUpdater::global().start_background_check(app_handle).await;