Compare commits

...
Author SHA1 Message Date
Tunglies 7dfaf3221c feat(updater): stage updates for a one-action restart
A daily cycle (first check 10s after start, gated by auto_check_update)
checks the server and stages the current offer's installer under a name
stamped with its version: only a surviving future publishes the staged
file, and a stage that no longer verifies against the offer is replaced.
The staged version is exposed through the get_staged_update command and
the verge://staged-update-changed event, so the update button becomes a
single restart action when the installer is ready. An install displaces
the cycle; a cancel never touches staged bytes, and turning
auto_check_update off stops new downloads without a discard protocol.
2026-11-27 22:41:08 +08:00
Tunglies 11af96dba1 refactor(updater): drop the prefetch cache and the daily cycle
The cache's consumer, the startup auto-install UI, was retired in
#8747; what remained was a faster dialog install for later-session
clicks. That did not carry the cost: every cache function, the
discard handshake with the config write lock, the daily tick, and
a persistent installer-sized directory for users who never install.

The actor now serves Install and Cancel only: the dialog install
always downloads with progress events, which the dialog already
renders, and auto_check_update keeps gating the frontend's own
update check.
2026-11-27 22:07:17 +08:00
Tunglies 7ba832ac2f refactor(updater): drop the cache metadata sidecar
The sidecar's version filter duplicated what Update::verify already
enforces: the plugin's signature binds the release version, so bytes
cached from an earlier offer fail verification for the current one.
Dropping it costs one full-bin read per release transition and leaves
the cache as a single file published by one rename.
2026-11-27 21:52:19 +08:00
Tunglies 9319a4894a fix(updater): keep the actor recoverable and the discard durable
Three failure-semantics gaps in the actor refactor:

- The blocking cache writer published the cache inside a task that a
  preemption detaches, so a discard could delete the cache, ack the
  config-write holder, and still leave a published cache behind it.
  The rename and metadata write now run on the actor after the
  blocking write's await, so only a surviving future can publish.
- The discard ack awaited a bulk unlink while the executor held the
  config write lock. The cache is now invalidated by an O(1) rename
  and unlinked detached.
- A panic in the actor ended all updating for the rest of the
  process; the global panic hook logs it, but nothing recovered. The
  loop now runs catch_unwind epochs, restarting with the mailbox and
  the daily check backed off.
2026-11-27 16:21:01 +08:00
Tunglies b68438556a refactor(updater): own the updater state in a single actor 2026-11-27 16:00:55 +08:00
12 changed files with 491 additions and 248 deletions
+15 -2
View File
@@ -66,7 +66,8 @@ pub async fn install_update(
on_event: Channel<DownloadEvent>,
) -> CmdResult<InstallUpdateOutcome> {
SilentUpdater::global()
.install_update(&app_handle, &version, |event| {
.ok_or("silent updater is not running")?
.install_update(&app_handle, &version, move |event| {
let _ = on_event.send(event);
})
.await
@@ -76,7 +77,19 @@ pub async fn install_update(
#[tauri::command]
#[specta::specta]
pub fn cancel_update_download() {
SilentUpdater::global().cancel_download();
if let Some(updater) = SilentUpdater::global() {
updater.cancel_download();
}
}
#[tauri::command]
#[specta::specta]
pub async fn get_staged_update() -> CmdResult<Option<std::string::String>> {
SilentUpdater::global()
.ok_or("silent updater is not running")?
.staged_version()
.await
.stringify_err()
}
#[tauri::command]
+6
View File
@@ -74,6 +74,12 @@ impl Handle {
Self::send_event(FrontendEvent::ProfileUpdateCompleted { uid });
}
/// A verified installer became ready (or was cleared); the frontend refetches the staged
/// version.
pub fn notify_staged_update_changed() {
Self::send_event(FrontendEvent::StagedUpdateChanged);
}
pub fn notice(status: NoticeStatus, message: impl Into<Arc<str>>) {
Self::send_event(FrontendEvent::NoticeMessage {
status,
@@ -35,6 +35,7 @@ pub enum FrontendEvent<'a> {
state: crate::core::runstate::RunStateView,
},
PendingFailuresChanged,
StagedUpdateChanged,
#[cfg(target_os = "linux")]
ThemeChanged {
theme: tauri::Theme,
@@ -408,6 +409,11 @@ fn sample_frontend_events(uid: &str) -> Vec<(FrontendEvent<'_>, &'static str, se
"verge://pending-failures-changed",
json!(null),
),
(
FrontendEvent::StagedUpdateChanged,
"verge://staged-update-changed",
json!(null),
),
(
FrontendEvent::ProfileChanged {
current_profile_id: uid,
@@ -460,6 +466,7 @@ frontend_events! {
profile_completed: ProfileUpdatePayload = "profile-update-completed", FrontendEvent::ProfileUpdateCompleted { uid } => ProfileUpdatePayload { uid: uid.to_string() };
run_state: crate::core::runstate::RunStateView = "verge://run-state-changed", FrontendEvent::RunStateChanged { state } => state;
pending_failures: () = "verge://pending-failures-changed", FrontendEvent::PendingFailuresChanged => ();
staged_update: () = "verge://staged-update-changed", FrontendEvent::StagedUpdateChanged => ();
}
#[derive(serde::Serialize, specta::Type)]
+416 -230
View File
@@ -1,20 +1,23 @@
use crate::{config::Config, singleton, utils::dirs};
use crate::{config::Config, core::handle::Handle, utils::dirs};
use anyhow::{Context as _, Result};
use clash_verge_logging::{Type, logging};
use parking_lot::Mutex;
use serde::{Deserialize, Serialize};
use futures::FutureExt as _;
use serde::Serialize;
use std::{
panic::AssertUnwindSafe,
path::PathBuf,
sync::atomic::{AtomicU64, Ordering},
sync::{
OnceLock,
atomic::{AtomicU64, Ordering},
},
time::Duration,
};
use tauri_plugin_updater::{Update, UpdaterExt as _};
use tokio_util::sync::CancellationToken;
use tokio::sync::{mpsc, oneshot};
/// App-global handle to the updater actor, the single task that runs every updater operation.
pub struct SilentUpdater {
manual_cancel: Mutex<Option<CancellationToken>>,
background_cancel: Mutex<Option<CancellationToken>>,
download_lock: tokio::sync::Mutex<()>,
tx: mpsc::Sender<Cmd>,
}
#[derive(Serialize, specta::Type)]
@@ -25,120 +28,153 @@ pub enum InstallUpdateOutcome {
UpdateChanged,
}
singleton!(SilentUpdater, SILENT_UPDATER);
static UPDATER: OnceLock<SilentUpdater> = OnceLock::new();
enum Cmd {
Install {
version: String,
on_event: Box<dyn Fn(DownloadEvent) + Send + Sync>,
reply: oneshot::Sender<Result<InstallUpdateOutcome>>,
},
Cancel,
StagedVersion {
reply: oneshot::Sender<Option<String>>,
},
}
/// What wakes the idle actor.
enum Wake {
Cmd(Cmd),
DailyCheck,
}
/// How a background cycle ended: `Displaced` carries the command that dropped it.
enum CycleEnd {
Completed(Result<Option<String>>),
Displaced(Cmd),
}
/// How a dialog install's prepare phase ended.
enum Prepared {
/// The update record with its verified bytes, or `None` when the offer changed.
Ready(Option<Box<(Update, Vec<u8>)>>),
Failed(anyhow::Error),
/// Preempted by a cancel; the work future is already dropped.
Dropped,
}
impl SilentUpdater {
const fn new() -> Self {
Self {
manual_cancel: Mutex::new(None),
background_cancel: Mutex::new(None),
download_lock: tokio::sync::Mutex::const_new(()),
}
/// Spawns the updater actor and installs the app-global handle.
pub fn start(app_handle: tauri::AppHandle) -> &'static Self {
UPDATER.get_or_init(|| {
let (tx, rx) = mpsc::channel(16);
tokio::spawn(Self::run(app_handle, rx));
Self { tx }
})
}
/// `None` only before `start`, which setup runs before any command can arrive.
pub fn global() -> Option<&'static Self> {
UPDATER.get()
}
}
#[derive(Serialize, Deserialize)]
struct UpdateCacheMeta {
version: String,
}
impl SilentUpdater {
fn cache_dir() -> Result<PathBuf> {
fn staging_dir() -> Result<PathBuf> {
Ok(dirs::app_home_dir()?.join("update_cache"))
}
/// 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<u8>, version: &str) -> Result<()> {
let cache_dir = Self::cache_dir()?;
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");
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 };
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",
meta.version,
bytes.len()
);
Ok(())
})
.await?
}
async fn read_cache_bytes() -> Result<Vec<u8>> {
let bin_path = Self::cache_dir()?.join("pending_update.bin");
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<UpdateCacheMeta> {
let meta_path = Self::cache_dir()?.join("pending_update.json");
let content = std::fs::read_to_string(meta_path)?;
Ok(serde_json::from_str(&content)?)
}
async fn delete_cache() {
if let Ok(cache_dir) = Self::cache_dir()
&& cache_dir.exists()
{
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.
async fn verified_cache(update: &Update) -> Option<Vec<u8>> {
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;
/// Writes the installer under a name stamped with the version it was staged for, through
/// a temp file so a crash leaves no partial file; installer-sized IO stays off the async
/// runtime. Only the detachable blocking task writes the temp file — the rename that
/// stages it runs after its await, so a command preempting this future cannot publish
/// behind the preemption.
async fn write_staged(bytes: Vec<u8>, version: &str) -> Result<()> {
let staging_dir = Self::staging_dir()?;
let bin_name = staged_file_name(version);
let bin_path = staging_dir.join(&bin_name);
let tmp_path = staging_dir.join(format!("{bin_name}.tmp"));
let write_tmp = {
let staging_dir = staging_dir.clone();
let tmp_path = tmp_path.clone();
move || -> Result<()> {
std::fs::create_dir_all(&staging_dir)
.with_context(|| format!("failed to create update staging directory {}", staging_dir.display()))?;
std::fs::write(&tmp_path, &bytes)
.with_context(|| format!("failed to write update staging file {}", tmp_path.display()))?;
Ok(())
}
};
let bytes = if meta.version == update.version {
Self::read_cache_bytes().await.and_then(|bytes| {
tokio::task::spawn_blocking(write_tmp).await??;
// Metadata-sized, so inline on the actor thread rather than a detachable task.
std::fs::rename(&tmp_path, &bin_path)
.with_context(|| format!("failed to publish update staging file {}", bin_path.display()))?;
Ok(())
}
/// Returns the staged installer for `update`: the staged name carries the version it was
/// staged for, and the plugin's `verify` binds the bytes to the signed release — both
/// must agree with the current offer. A stage that fails either is removed.
async fn staged_bytes(update: &Update) -> Option<Vec<u8>> {
// A quiet miss for the common nothing-staged case; only a present-but-bad file logs.
let Ok(bin_path) = Self::staging_dir().map(|dir| dir.join(staged_file_name(&update.version))) else {
return None;
};
if !bin_path.exists() {
return None;
}
let read = tokio::task::spawn_blocking(move || {
std::fs::read(&bin_path).with_context(|| format!("failed to read staged update {}", bin_path.display()))
})
.await;
let bytes = match read {
Ok(result) => result.and_then(|bytes| {
update.verify(&bytes)?;
Ok(bytes)
})
} else {
Err(anyhow::anyhow!("server offers v{}", update.version))
}),
Err(e) => Err(anyhow::anyhow!("staged update read failed: {e}")),
};
match bytes {
Ok(bytes) => Some(bytes),
Err(e) => {
logging!(
info,
Type::System,
"Update cache v{} is unusable: {e:#}, cleaning up",
meta.version
);
Self::delete_cache().await;
logging!(info, Type::System, "Staged update is unusable: {e:#}, cleaning up");
Self::delete_staged().await;
None
}
}
}
/// Removes the staging directory; a failed removal leaves bytes the next cycle
/// re-verifies and replaces.
async fn delete_staged() {
if let Ok(staging_dir) = Self::staging_dir()
&& staging_dir.exists()
{
let display = staging_dir.display().to_string();
match tokio::task::spawn_blocking(move || std::fs::remove_dir_all(&staging_dir)).await {
Ok(Ok(())) => logging!(info, Type::System, "Staged update removed"),
Ok(Err(e)) => logging!(warn, Type::System, "Failed to remove staged update {display}: {e}"),
Err(e) => logging!(warn, Type::System, "Failed to remove staged update {display}: {e}"),
}
}
}
}
/// Filesystem-safe staging name for `version`: the name itself asserts which version the
/// staged installer belongs to, so an announcement can never adopt a stage of another
/// version regardless of signature details.
fn staged_file_name(version: &str) -> String {
let sanitized: String = version
.chars()
.map(|c| {
if c.is_ascii_alphanumeric() || matches!(c, '.' | '-' | '_') {
c
} else {
'_'
}
})
.collect();
format!("pending_update_{sanitized}.bin")
}
pub fn is_build_to_stable(current: &str, remote: &str) -> bool {
@@ -179,6 +215,8 @@ const MIRRORS: [&str; 2] = ["https://update.hwdns.net/", "https://gh-proxy.org/"
/// A source delivering less than this per window is dropped for the next one.
const MIN_PROGRESS: u64 = 1024 * 1024;
const PROGRESS_WINDOW: Duration = Duration::from_secs(30);
/// How long the actor waits after a panic before re-arming the daily check.
const PANIC_BACKOFF: Duration = Duration::from_secs(600);
#[cfg(target_os = "windows")]
const INSTALL_TIMEOUT: Duration = Duration::from_secs(30);
#[cfg(not(target_os = "windows"))]
@@ -268,18 +306,18 @@ impl SilentUpdater {
let updater_builder = app_handle.updater_builder();
#[cfg(target_os = "windows")]
let updater_builder = {
let verge_lang = Config::verge().await.latest_arc().language.clone();
let verge_lang = crate::config::Config::verge().await.latest_arc().language.clone();
let lang_id = nsis_language_id(&clash_verge_i18n::current_language(verge_lang.as_deref()));
updater_builder.installer_arg(format!("/LANG={lang_id}"))
};
Ok(updater_builder.build()?.check().await?)
}
/// Installs verified bytes, dropping the cache first so a failure leaves nothing to
/// re-trigger. A timeout abandons the await, not the detached install task; a successful
/// Windows install exits the process inside the plugin (#2558).
/// Installs verified bytes, consuming the staging copy first so a failed install leaves
/// nothing claiming readiness. 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<u8>) -> Result<()> {
Self::delete_cache().await;
Self::delete_staged().await;
let install = tokio::task::spawn_blocking(move || update.install(&bytes));
match tokio::time::timeout(INSTALL_TIMEOUT, install).await {
Ok(result) => Ok(result??),
@@ -288,98 +326,178 @@ impl SilentUpdater {
)),
}
}
}
/// 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.
impl SilentUpdater {
/// Installs `version` for the update dialog, reusing the staged installer when it holds
/// that version; a changed offer must be confirmed again before downloading or
/// installing it.
pub async fn install_update(
&self,
app_handle: &tauri::AppHandle,
// The actor owns the app handle; the parameter keeps the command's call shape.
_app_handle: &tauri::AppHandle,
version: &str,
on_event: impl Fn(DownloadEvent) + Sync,
on_event: impl Fn(DownloadEvent) + Send + Sync + 'static,
) -> Result<InstallUpdateOutcome> {
let cancel = CancellationToken::new();
{
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),
() = cancel.cancelled() => None,
};
// `cancel_download` cancels under the lock, so once the token is taken back its state is
// final; a cancel during the last synchronous poll of `prepare_install` still wins.
self.manual_cancel.lock().take();
let Some(prepared) = prepared.filter(|_| !cancel.is_cancelled()).transpose()? else {
logging!(info, Type::System, "Update v{version} cancelled");
return Ok(InstallUpdateOutcome::Cancelled);
};
let Some((update, bytes)) = prepared else {
return Ok(InstallUpdateOutcome::UpdateChanged);
};
logging!(info, Type::System, "Installing update v{version}...");
on_event(DownloadEvent::Installing);
Self::install(update, bytes).await?;
Ok(InstallUpdateOutcome::Installed)
}
async fn prepare_install(
&self,
app_handle: &tauri::AppHandle,
version: &str,
on_event: &(impl Fn(DownloadEvent) + Sync),
) -> Result<Option<(Update, Vec<u8>)>> {
let Some(update) = Self::check(app_handle)
.await?
.filter(|update| update.version == version)
else {
return Ok(None);
};
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?,
};
Ok(Some((update, bytes)))
let (reply, reply_rx) = oneshot::channel();
self.tx
.send(Cmd::Install {
version: version.to_owned(),
on_event: Box::new(on_event),
reply,
})
.await
.map_err(|_| anyhow::anyhow!("updater stopped"))?;
reply_rx
.await
.unwrap_or_else(|_| Err(anyhow::anyhow!("updater stopped")))
}
pub fn cancel_download(&self) {
let mut slot = self.manual_cancel.lock();
if let Some(cancel) = slot.take() {
cancel.cancel();
}
// try_send: a cancel must never block, and the mailbox never fills in practice.
let _ = self.tx.try_send(Cmd::Cancel);
}
/// Drops the downloaded update and aborts a background download in flight.
pub async fn discard_pending(&self) {
let cancel = self.background_cancel.lock().take();
if let Some(cancel) = cancel {
cancel.cancel();
}
Self::delete_cache().await;
/// The version whose installer is staged and ready for a one-action restart, or `None`.
pub async fn staged_version(&self) -> Result<Option<String>> {
let (reply, reply_rx) = oneshot::channel();
self.tx
.send(Cmd::StagedVersion { reply })
.await
.map_err(|_| anyhow::anyhow!("updater stopped"))?;
Ok(reply_rx.await.unwrap_or(None))
}
}
impl SilentUpdater {
async fn check_and_download(&self, app_handle: &tauri::AppHandle) -> Result<()> {
// Registered before reading the switch, so `discard_pending` either cancels it or ran first.
let cancel = CancellationToken::new();
*self.background_cancel.lock() = Some(cancel.clone());
/// The actor's supervisor: one `serve` epoch at a time. A panic drops the epoch — its
/// in-flight work and any reply it still owed — but not the mailbox or the staged
/// version, so the actor restarts instead of leaving updating dead for the rest of the
/// process.
async fn run(app_handle: tauri::AppHandle, mut rx: mpsc::Receiver<Cmd>) {
logging!(info, Type::System, "Silent updater: background task started");
let mut next_check = tokio::time::Instant::now() + Duration::from_secs(10);
let mut staged: Option<String> = None;
loop {
let epoch = AssertUnwindSafe(Self::serve(&app_handle, &mut rx, &mut next_check, &mut staged));
match epoch.catch_unwind().await {
// The mailbox closed; the handle holds the only sender, so this is shutdown.
Ok(()) => return,
Err(_) => {
// The global panic hook logged the payload; this marks the recovery. The
// epoch future is dropped during the unwind, ending its borrows, so the
// mailbox, the schedule, and the staged version below are intact.
logging!(error, Type::System, "Silent updater: actor panicked, restarting");
// Back the daily check off so a persistently panicking path cannot hot-loop.
next_check = next_check.max(tokio::time::Instant::now() + PANIC_BACKOFF);
}
}
}
}
/// The actor loop: idle until a command or the daily check, then run the work. A cancel
/// during the install's prepare phase drops the work future; a second install is
/// declined in place; an install displaces the daily cycle.
async fn serve(
app_handle: &tauri::AppHandle,
rx: &mut mpsc::Receiver<Cmd>,
next_check: &mut tokio::time::Instant,
staged: &mut Option<String>,
) {
loop {
let mut wake = tokio::select! {
maybe = rx.recv() => match maybe {
Some(cmd) => Wake::Cmd(cmd),
None => return,
},
_ = tokio::time::sleep_until(*next_check) => Wake::DailyCheck,
};
loop {
match wake {
Wake::Cmd(Cmd::Install {
version,
on_event,
reply,
}) => {
Self::run_install(app_handle, &version, on_event, reply, rx, staged).await;
break;
}
// The dialog's cancel only addresses a running install; idle it stops nothing.
Wake::Cmd(Cmd::Cancel) => break,
Wake::Cmd(Cmd::StagedVersion { reply }) => {
let _ = reply.send(staged.clone());
break;
}
Wake::DailyCheck => {
let end = Self::run_background_cycle(app_handle, rx, staged).await;
*next_check = tokio::time::Instant::now() + Duration::from_secs(24 * 60 * 60);
match end {
CycleEnd::Completed(Ok(new_staged)) => {
if *staged != new_staged {
*staged = new_staged;
Handle::notify_staged_update_changed();
}
break;
}
CycleEnd::Completed(Err(e)) => {
logging!(warn, Type::System, "Silent updater: cycle error: {e}");
break;
}
CycleEnd::Displaced(cmd) => wake = Wake::Cmd(cmd),
}
}
}
}
}
}
/// Runs one daily cycle, pre-empted by user commands: a cancel and a staged-version
/// query are answered in place; an install drops the cycle, and the cycle future is
/// gone before the follow-up dispatch runs.
async fn run_background_cycle(
app_handle: &tauri::AppHandle,
rx: &mut mpsc::Receiver<Cmd>,
staged: &Option<String>,
) -> CycleEnd {
let cycle = Self::stage_update(app_handle);
tokio::pin!(cycle);
let mut mailbox_open = true;
loop {
let maybe = tokio::select! {
biased;
maybe = rx.recv(), if mailbox_open => maybe,
result = &mut cycle => return CycleEnd::Completed(result),
};
let Some(cmd) = maybe else {
mailbox_open = false;
continue;
};
match cmd {
Cmd::Cancel => {}
Cmd::StagedVersion { reply } => {
let _ = reply.send(staged.clone());
}
Cmd::Install { .. } => return CycleEnd::Displaced(cmd),
}
}
}
/// Checks for an update and stages its installer for a one-action restart: the staged
/// bytes are downloaded only when they no longer verify against the current offer.
async fn stage_update(app_handle: &tauri::AppHandle) -> Result<Option<String>> {
let auto_check = Config::verge().await.latest_arc().auto_check_update.unwrap_or(true);
if !auto_check {
logging!(debug, Type::System, "Silent update skipped: auto_check_update is false");
return Ok(());
return Ok(None);
}
logging!(info, Type::System, "Silent updater: checking for updates...");
let updater = app_handle.updater()?;
let update = match updater.check().await {
let update = match app_handle.updater()?.check().await {
Ok(Some(update)) => update,
Ok(None) => {
logging!(info, Type::System, "Silent updater: no update available");
return Ok(());
return Ok(None);
}
Err(e) => {
logging!(warn, Type::System, "Silent updater: check failed: {e}");
@@ -387,71 +505,139 @@ impl SilentUpdater {
}
};
let version = update.version.as_str();
let version = update.version.clone();
logging!(info, Type::System, "Silent updater: update available: v{version}");
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");
if Self::staged_bytes(&update).await.is_some() {
logging!(info, Type::System, "Silent updater: v{version} already staged");
} else {
logging!(info, Type::System, "Silent updater: downloading v{version}...");
let downloaded = tokio::select! {
bytes = download(&update, |_| {}) => Some(bytes),
() = cancel.cancelled() => None,
};
let Some(bytes) = downloaded else {
logging!(info, Type::System, "Silent updater: download cancelled");
return Ok(());
};
let bytes = bytes?;
let bytes = download(&update, |_| {}).await?;
logging!(info, Type::System, "Silent updater: download complete");
Self::write_cache(bytes, version).await?;
// Remove any stage left by an earlier offer before publishing the new one.
Self::delete_staged().await;
Self::write_staged(bytes, &version).await?;
logging!(info, Type::System, "Silent updater: v{version} ready to install");
}
drop(download_guard);
// 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().await;
return Ok(());
}
logging!(
info,
Type::System,
"Silent updater: v{version} ready to install from the update dialog"
);
Ok(())
Ok(Some(version))
}
pub async fn start_background_check(&self, app_handle: tauri::AppHandle) {
// Permanent watcher: daily update cycles for the lifetime of the app.
logging!(info, Type::System, "Silent updater: background task started");
tokio::time::sleep(std::time::Duration::from_secs(10)).await;
loop {
if let Err(e) = self.check_and_download(&app_handle).await {
logging!(warn, Type::System, "Silent updater: cycle error: {e}");
/// One dialog install from prepare to install; every exit path answers `reply`.
async fn run_install(
app_handle: &tauri::AppHandle,
version: &str,
on_event: Box<dyn Fn(DownloadEvent) + Send + Sync>,
reply: oneshot::Sender<Result<InstallUpdateOutcome>>,
rx: &mut mpsc::Receiver<Cmd>,
staged: &Option<String>,
) {
match Self::prepare_cancellable(app_handle, version, on_event.as_ref(), rx, staged).await {
// The prepare work is already dropped, so a cancel racing the last poll still wins.
Prepared::Dropped => {
logging!(info, Type::System, "Update v{version} cancelled");
let _ = reply.send(Ok(InstallUpdateOutcome::Cancelled));
}
Prepared::Failed(e) => {
let _ = reply.send(Err(e));
}
Prepared::Ready(None) => {
let _ = reply.send(Ok(InstallUpdateOutcome::UpdateChanged));
}
Prepared::Ready(Some(pair)) => {
let (update, bytes) = *pair;
logging!(info, Type::System, "Installing update v{version}...");
on_event(DownloadEvent::Installing);
let result = Self::finish_install(update, bytes, rx, staged).await;
let _ = reply.send(result.map(|_| InstallUpdateOutcome::Installed));
}
tokio::time::sleep(std::time::Duration::from_secs(24 * 60 * 60)).await;
}
}
/// The cancellable prepare phase: check, version filter, staged reuse or download. A
/// second install is declined in place; a cancel drops the work.
async fn prepare_cancellable(
app_handle: &tauri::AppHandle,
version: &str,
on_event: &(impl Fn(DownloadEvent) + Sync + ?Sized),
rx: &mut mpsc::Receiver<Cmd>,
staged: &Option<String>,
) -> Prepared {
let prepare = Self::prepare_install(app_handle, version, on_event);
tokio::pin!(prepare);
let mut mailbox_open = true;
loop {
let maybe = tokio::select! {
biased;
maybe = rx.recv(), if mailbox_open => maybe,
prepared = &mut prepare => return match prepared {
Ok(prepared) => Prepared::Ready(prepared.map(Box::new)),
Err(e) => Prepared::Failed(e),
},
};
let Some(cmd) = maybe else {
mailbox_open = false;
continue;
};
match cmd {
Cmd::Cancel => return Prepared::Dropped,
Cmd::StagedVersion { reply } => {
let _ = reply.send(staged.clone());
}
Cmd::Install { reply, .. } => Self::decline_install(reply),
}
}
}
async fn prepare_install(
app_handle: &tauri::AppHandle,
version: &str,
on_event: &(impl Fn(DownloadEvent) + Sync + ?Sized),
) -> Result<Option<(Update, Vec<u8>)>> {
let Some(update) = Self::check(app_handle)
.await?
.filter(|update| update.version == version)
else {
return Ok(None);
};
let bytes = match Self::staged_bytes(&update).await {
Some(bytes) => bytes,
None => download(&update, on_event).await?,
};
Ok(Some((update, bytes)))
}
/// The install phase: once `install()` started it cannot be cancelled (the installer may
/// already run); the mailbox still gets answers while it finishes.
async fn finish_install(
update: Update,
bytes: Vec<u8>,
rx: &mut mpsc::Receiver<Cmd>,
staged: &Option<String>,
) -> Result<()> {
let install = Self::install(update, bytes);
tokio::pin!(install);
let mut mailbox_open = true;
loop {
let maybe = tokio::select! {
result = &mut install => return result,
maybe = rx.recv(), if mailbox_open => maybe,
};
let Some(cmd) = maybe else {
mailbox_open = false;
continue;
};
match cmd {
Cmd::Cancel => {}
Cmd::StagedVersion { reply } => {
let _ = reply.send(staged.clone());
}
Cmd::Install { reply, .. } => Self::decline_install(reply),
}
}
}
fn decline_install(reply: oneshot::Sender<Result<InstallUpdateOutcome>>) {
let _ = reply.send(Err(anyhow::anyhow!("an update install is already in progress")));
}
}
#[cfg(test)]
+2 -8
View File
@@ -6,10 +6,7 @@ use crate::{
snapshot::{capture_config_files, restore_files},
},
core::auto_backup::AutoBackupManager,
core::{
CoreManager, SilentUpdater, autostart, hotkey, lightweight, logger, manager::ConfigUpdateGuard, proxy_control,
tray,
},
core::{CoreManager, autostart, hotkey, lightweight, logger, manager::ConfigUpdateGuard, proxy_control, tray},
};
use anyhow::Result;
use clash_verge_draft::DraftTransaction;
@@ -162,10 +159,7 @@ pub(super) async fn apply(config_write: &MutexGuard<'_, ()>, patch: Patch<'_>, e
}
transaction.commit();
match patch {
Patch::Verge { patch, .. } => {
if patch.auto_check_update == Some(false) {
SilentUpdater::global().discard_pending().await;
}
Patch::Verge { .. } => {
if effects.contains(&Effect::ClashConfig) {
announce(Refresh::Clash);
}
+1
View File
@@ -20,6 +20,7 @@ pub fn builder() -> tauri_specta::Builder<tauri::Wry> {
cmd::restart_app,
cmd::install_update,
cmd::cancel_update_download,
cmd::get_staged_update,
cmd::restart_core,
cmd::upgrade_clash_core,
cmd::get_runtime_state,
+1 -5
View File
@@ -159,11 +159,7 @@ fn init_silent_updater() {
logging!(debug, Type::Setup, "Initializing silent updater...");
let app_handle = Handle::app_handle();
let app_handle = app_handle.clone();
tokio::spawn(async move {
SilentUpdater::global().start_background_check(app_handle).await;
});
SilentUpdater::start(Handle::app_handle().clone());
logging!(info, Type::Setup, "Silent updater initialized");
}
+27 -3
View File
@@ -1,8 +1,11 @@
import { Button } from '@mui/material'
import { useLockFn } from 'ahooks'
import { useRef } from 'react'
import { DialogRef } from '@/components/base'
import { useUpdate } from '@/hooks/use-update'
import { installUpdate, restartApp } from '@/services/cmds'
import { showNotice } from '@/services/notice-service'
import { UpdateViewer } from '../setting/mods/update-viewer'
@@ -14,10 +17,27 @@ export const UpdateButton = (props: Props) => {
const { className } = props
const viewerRef = useRef<DialogRef>(null)
const { updateInfo } = useUpdate()
const { updateInfo, stagedVersion } = useUpdate()
const onRestartToUpdate = useLockFn(async (version: string) => {
try {
const outcome = await installUpdate(version, () => {})
if (outcome === 'installed') {
await restartApp()
} else {
viewerRef.current?.open()
}
} catch (err) {
showNotice.error(err)
}
})
if (!updateInfo?.available) return null
// The staged installer makes the install near-instant, so the click is the whole action;
// any other outcome falls back to the dialog.
const ready = stagedVersion != null && stagedVersion === updateInfo.version
return (
<>
<UpdateViewer ref={viewerRef} />
@@ -27,9 +47,13 @@ export const UpdateButton = (props: Props) => {
variant="contained"
size="small"
className={className}
onClick={() => viewerRef.current?.open()}
onClick={
ready
? () => onRestartToUpdate(updateInfo.version)
: () => viewerRef.current?.open()
}
>
New
{ready ? 'Restart' : 'New'}
</Button>
</>
)
+7
View File
@@ -1,3 +1,4 @@
import { getStagedUpdate } from '@/services/cmds'
import { fetchCacheData, setCacheData, useQuery } from '@/services/query-client'
import { checkForUpdate } from '@/services/update'
@@ -54,10 +55,16 @@ export const useUpdate = (enabled: boolean = true) => {
refetchOnReconnect: false,
})
const { data: stagedVersion } = useQuery({
queryKey: ['getStagedUpdate'],
queryFn: () => getStagedUpdate(),
})
return {
updateInfo,
checkUpdate,
loading: isValidating,
lastCheckUpdate: lastCheckUpdate ?? null,
stagedVersion: stagedVersion ?? null,
}
}
+3
View File
@@ -32,6 +32,7 @@ export const commands = {
onEvent,
}),
cancelUpdateDownload: () => __TAURI_INVOKE<void>('cancel_update_download'),
getStagedUpdate: () => __TAURI_INVOKE<string | null>('get_staged_update'),
restartCore: () => __TAURI_INVOKE<null>('restart_core'),
/** Replaces the managed core binary atomically instead of letting mihomo overwrite itself. */
upgradeClashCore: (force: boolean) =>
@@ -1141,6 +1142,7 @@ export type VergeEventPayloads_Deserialize = {
'profile-update-completed': ProfileUpdatePayload
'verge://run-state-changed': RunStateView_Deserialize
'verge://pending-failures-changed': null
'verge://staged-update-changed': null
}
export type VergeEventPayloads_Serialize = {
@@ -1155,6 +1157,7 @@ export type VergeEventPayloads_Serialize = {
'profile-update-completed': ProfileUpdatePayload
'verge://run-state-changed': RunStateView_Serialize
'verge://pending-failures-changed': null
'verge://staged-update-changed': null
}
export type WebDavFile = {
+2
View File
@@ -81,6 +81,8 @@ export const createEventBus = (deps: BusHandlerDeps) => {
if (payload.mode !== 'NotRunning') forgetShownStartupError()
},
'verge://pending-failures-changed': () => deps.readPendingFailures(),
'verge://staged-update-changed': () =>
deps.revalidateKeys(['getStagedUpdate']),
[TEST_ALL_EVENT]: () => deps.dispatch({ type: 'testAll/requested' }),
}
+4
View File
@@ -306,6 +306,10 @@ export async function cancelUpdateDownload() {
return commands.cancelUpdateDownload()
}
export async function getStagedUpdate() {
return commands.getStagedUpdate()
}
export async function getAppDir() {
return commands.getAppDir()
}