mirror of
https://github.com/clash-verge-rev/clash-verge-rev.git
synced 2026-11-28 00:10:05 +08:00
Compare commits
5
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7dfaf3221c | ||
|
|
11af96dba1 | ||
|
|
7ba832ac2f | ||
|
|
9319a4894a | ||
|
|
b68438556a |
@@ -66,7 +66,8 @@ pub async fn install_update(
|
|||||||
on_event: Channel<DownloadEvent>,
|
on_event: Channel<DownloadEvent>,
|
||||||
) -> CmdResult<InstallUpdateOutcome> {
|
) -> CmdResult<InstallUpdateOutcome> {
|
||||||
SilentUpdater::global()
|
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);
|
let _ = on_event.send(event);
|
||||||
})
|
})
|
||||||
.await
|
.await
|
||||||
@@ -76,7 +77,19 @@ pub async fn install_update(
|
|||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
#[specta::specta]
|
#[specta::specta]
|
||||||
pub fn cancel_update_download() {
|
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]
|
#[tauri::command]
|
||||||
|
|||||||
@@ -74,6 +74,12 @@ impl Handle {
|
|||||||
Self::send_event(FrontendEvent::ProfileUpdateCompleted { uid });
|
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>>) {
|
pub fn notice(status: NoticeStatus, message: impl Into<Arc<str>>) {
|
||||||
Self::send_event(FrontendEvent::NoticeMessage {
|
Self::send_event(FrontendEvent::NoticeMessage {
|
||||||
status,
|
status,
|
||||||
|
|||||||
@@ -35,6 +35,7 @@ pub enum FrontendEvent<'a> {
|
|||||||
state: crate::core::runstate::RunStateView,
|
state: crate::core::runstate::RunStateView,
|
||||||
},
|
},
|
||||||
PendingFailuresChanged,
|
PendingFailuresChanged,
|
||||||
|
StagedUpdateChanged,
|
||||||
#[cfg(target_os = "linux")]
|
#[cfg(target_os = "linux")]
|
||||||
ThemeChanged {
|
ThemeChanged {
|
||||||
theme: tauri::Theme,
|
theme: tauri::Theme,
|
||||||
@@ -408,6 +409,11 @@ fn sample_frontend_events(uid: &str) -> Vec<(FrontendEvent<'_>, &'static str, se
|
|||||||
"verge://pending-failures-changed",
|
"verge://pending-failures-changed",
|
||||||
json!(null),
|
json!(null),
|
||||||
),
|
),
|
||||||
|
(
|
||||||
|
FrontendEvent::StagedUpdateChanged,
|
||||||
|
"verge://staged-update-changed",
|
||||||
|
json!(null),
|
||||||
|
),
|
||||||
(
|
(
|
||||||
FrontendEvent::ProfileChanged {
|
FrontendEvent::ProfileChanged {
|
||||||
current_profile_id: uid,
|
current_profile_id: uid,
|
||||||
@@ -460,6 +466,7 @@ frontend_events! {
|
|||||||
profile_completed: ProfileUpdatePayload = "profile-update-completed", FrontendEvent::ProfileUpdateCompleted { uid } => ProfileUpdatePayload { uid: uid.to_string() };
|
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;
|
run_state: crate::core::runstate::RunStateView = "verge://run-state-changed", FrontendEvent::RunStateChanged { state } => state;
|
||||||
pending_failures: () = "verge://pending-failures-changed", FrontendEvent::PendingFailuresChanged => ();
|
pending_failures: () = "verge://pending-failures-changed", FrontendEvent::PendingFailuresChanged => ();
|
||||||
|
staged_update: () = "verge://staged-update-changed", FrontendEvent::StagedUpdateChanged => ();
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(serde::Serialize, specta::Type)]
|
#[derive(serde::Serialize, specta::Type)]
|
||||||
|
|||||||
+411
-225
@@ -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 anyhow::{Context as _, Result};
|
||||||
use clash_verge_logging::{Type, logging};
|
use clash_verge_logging::{Type, logging};
|
||||||
use parking_lot::Mutex;
|
use futures::FutureExt as _;
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::Serialize;
|
||||||
use std::{
|
use std::{
|
||||||
|
panic::AssertUnwindSafe,
|
||||||
path::PathBuf,
|
path::PathBuf,
|
||||||
sync::atomic::{AtomicU64, Ordering},
|
sync::{
|
||||||
|
OnceLock,
|
||||||
|
atomic::{AtomicU64, Ordering},
|
||||||
|
},
|
||||||
time::Duration,
|
time::Duration,
|
||||||
};
|
};
|
||||||
use tauri_plugin_updater::{Update, UpdaterExt as _};
|
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 {
|
pub struct SilentUpdater {
|
||||||
manual_cancel: Mutex<Option<CancellationToken>>,
|
tx: mpsc::Sender<Cmd>,
|
||||||
background_cancel: Mutex<Option<CancellationToken>>,
|
|
||||||
download_lock: tokio::sync::Mutex<()>,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Serialize, specta::Type)]
|
#[derive(Serialize, specta::Type)]
|
||||||
@@ -25,120 +28,153 @@ pub enum InstallUpdateOutcome {
|
|||||||
UpdateChanged,
|
UpdateChanged,
|
||||||
}
|
}
|
||||||
|
|
||||||
singleton!(SilentUpdater, SILENT_UPDATER);
|
static UPDATER: OnceLock<SilentUpdater> = OnceLock::new();
|
||||||
|
|
||||||
impl SilentUpdater {
|
enum Cmd {
|
||||||
const fn new() -> Self {
|
Install {
|
||||||
Self {
|
|
||||||
manual_cancel: Mutex::new(None),
|
|
||||||
background_cancel: Mutex::new(None),
|
|
||||||
download_lock: tokio::sync::Mutex::const_new(()),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Serialize, Deserialize)]
|
|
||||||
struct UpdateCacheMeta {
|
|
||||||
version: String,
|
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 {
|
impl SilentUpdater {
|
||||||
fn cache_dir() -> Result<PathBuf> {
|
/// 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()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl SilentUpdater {
|
||||||
|
fn staging_dir() -> Result<PathBuf> {
|
||||||
Ok(dirs::app_home_dir()?.join("update_cache"))
|
Ok(dirs::app_home_dir()?.join("update_cache"))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Writes the payload through a temp file so a crash leaves no partial `pending_update.bin`;
|
/// Writes the installer under a name stamped with the version it was staged for, through
|
||||||
/// installer-sized IO stays off the async runtime.
|
/// a temp file so a crash leaves no partial file; installer-sized IO stays off the async
|
||||||
async fn write_cache(bytes: Vec<u8>, version: &str) -> Result<()> {
|
/// runtime. Only the detachable blocking task writes the temp file — the rename that
|
||||||
let cache_dir = Self::cache_dir()?;
|
/// stages it runs after its await, so a command preempting this future cannot publish
|
||||||
let version = version.to_owned();
|
/// behind the preemption.
|
||||||
tokio::task::spawn_blocking(move || -> Result<()> {
|
async fn write_staged(bytes: Vec<u8>, version: &str) -> Result<()> {
|
||||||
std::fs::create_dir_all(&cache_dir)
|
let staging_dir = Self::staging_dir()?;
|
||||||
.with_context(|| format!("failed to create update cache directory {}", cache_dir.display()))?;
|
let bin_name = staged_file_name(version);
|
||||||
|
let bin_path = staging_dir.join(&bin_name);
|
||||||
let bin_path = cache_dir.join("pending_update.bin");
|
let tmp_path = staging_dir.join(format!("{bin_name}.tmp"));
|
||||||
let tmp_path = cache_dir.join("pending_update.bin.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)
|
std::fs::write(&tmp_path, &bytes)
|
||||||
.with_context(|| format!("failed to write update cache {}", tmp_path.display()))?;
|
.with_context(|| format!("failed to write update staging file {}", 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(())
|
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;
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
let bytes = if meta.version == update.version {
|
tokio::task::spawn_blocking(write_tmp).await??;
|
||||||
Self::read_cache_bytes().await.and_then(|bytes| {
|
// 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)?;
|
update.verify(&bytes)?;
|
||||||
Ok(bytes)
|
Ok(bytes)
|
||||||
})
|
}),
|
||||||
} else {
|
Err(e) => Err(anyhow::anyhow!("staged update read failed: {e}")),
|
||||||
Err(anyhow::anyhow!("server offers v{}", update.version))
|
|
||||||
};
|
};
|
||||||
match bytes {
|
match bytes {
|
||||||
Ok(bytes) => Some(bytes),
|
Ok(bytes) => Some(bytes),
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
logging!(
|
logging!(info, Type::System, "Staged update is unusable: {e:#}, cleaning up");
|
||||||
info,
|
Self::delete_staged().await;
|
||||||
Type::System,
|
|
||||||
"Update cache v{} is unusable: {e:#}, cleaning up",
|
|
||||||
meta.version
|
|
||||||
);
|
|
||||||
Self::delete_cache().await;
|
|
||||||
None
|
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 {
|
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.
|
/// A source delivering less than this per window is dropped for the next one.
|
||||||
const MIN_PROGRESS: u64 = 1024 * 1024;
|
const MIN_PROGRESS: u64 = 1024 * 1024;
|
||||||
const PROGRESS_WINDOW: Duration = Duration::from_secs(30);
|
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")]
|
#[cfg(target_os = "windows")]
|
||||||
const INSTALL_TIMEOUT: Duration = Duration::from_secs(30);
|
const INSTALL_TIMEOUT: Duration = Duration::from_secs(30);
|
||||||
#[cfg(not(target_os = "windows"))]
|
#[cfg(not(target_os = "windows"))]
|
||||||
@@ -268,18 +306,18 @@ impl SilentUpdater {
|
|||||||
let updater_builder = app_handle.updater_builder();
|
let updater_builder = app_handle.updater_builder();
|
||||||
#[cfg(target_os = "windows")]
|
#[cfg(target_os = "windows")]
|
||||||
let updater_builder = {
|
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()));
|
let lang_id = nsis_language_id(&clash_verge_i18n::current_language(verge_lang.as_deref()));
|
||||||
updater_builder.installer_arg(format!("/LANG={lang_id}"))
|
updater_builder.installer_arg(format!("/LANG={lang_id}"))
|
||||||
};
|
};
|
||||||
Ok(updater_builder.build()?.check().await?)
|
Ok(updater_builder.build()?.check().await?)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Installs verified bytes, dropping the cache first so a failure leaves nothing to
|
/// Installs verified bytes, consuming the staging copy first so a failed install leaves
|
||||||
/// re-trigger. A timeout abandons the await, not the detached install task; a successful
|
/// nothing claiming readiness. A timeout abandons the await, not the detached install
|
||||||
/// Windows install exits the process inside the plugin (#2558).
|
/// task; a successful Windows install exits the process inside the plugin (#2558).
|
||||||
async fn install(update: Update, bytes: Vec<u8>) -> Result<()> {
|
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));
|
let install = tokio::task::spawn_blocking(move || update.install(&bytes));
|
||||||
match tokio::time::timeout(INSTALL_TIMEOUT, install).await {
|
match tokio::time::timeout(INSTALL_TIMEOUT, install).await {
|
||||||
Ok(result) => Ok(result??),
|
Ok(result) => Ok(result??),
|
||||||
@@ -288,98 +326,178 @@ impl SilentUpdater {
|
|||||||
)),
|
)),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// Installs `version` for the update dialog, reusing the cache when it holds that version;
|
impl SilentUpdater {
|
||||||
/// A changed offer must be confirmed again before downloading or installing it.
|
/// 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(
|
pub async fn install_update(
|
||||||
&self,
|
&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,
|
version: &str,
|
||||||
on_event: impl Fn(DownloadEvent) + Sync,
|
on_event: impl Fn(DownloadEvent) + Send + Sync + 'static,
|
||||||
) -> Result<InstallUpdateOutcome> {
|
) -> Result<InstallUpdateOutcome> {
|
||||||
let cancel = CancellationToken::new();
|
let (reply, reply_rx) = oneshot::channel();
|
||||||
{
|
self.tx
|
||||||
let mut slot = self.manual_cancel.lock();
|
.send(Cmd::Install {
|
||||||
anyhow::ensure!(slot.is_none(), "an update install is already in progress");
|
version: version.to_owned(),
|
||||||
*slot = Some(cancel.clone());
|
on_event: Box::new(on_event),
|
||||||
}
|
reply,
|
||||||
let prepared = tokio::select! {
|
})
|
||||||
prepared = self.prepare_install(app_handle, version, &on_event) => Some(prepared),
|
.await
|
||||||
() = cancel.cancelled() => None,
|
.map_err(|_| anyhow::anyhow!("updater stopped"))?;
|
||||||
};
|
reply_rx
|
||||||
// `cancel_download` cancels under the lock, so once the token is taken back its state is
|
.await
|
||||||
// final; a cancel during the last synchronous poll of `prepare_install` still wins.
|
.unwrap_or_else(|_| Err(anyhow::anyhow!("updater stopped")))
|
||||||
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)))
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn cancel_download(&self) {
|
pub fn cancel_download(&self) {
|
||||||
let mut slot = self.manual_cancel.lock();
|
// try_send: a cancel must never block, and the mailbox never fills in practice.
|
||||||
if let Some(cancel) = slot.take() {
|
let _ = self.tx.try_send(Cmd::Cancel);
|
||||||
cancel.cancel();
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Drops the downloaded update and aborts a background download in flight.
|
/// The version whose installer is staged and ready for a one-action restart, or `None`.
|
||||||
pub async fn discard_pending(&self) {
|
pub async fn staged_version(&self) -> Result<Option<String>> {
|
||||||
let cancel = self.background_cancel.lock().take();
|
let (reply, reply_rx) = oneshot::channel();
|
||||||
if let Some(cancel) = cancel {
|
self.tx
|
||||||
cancel.cancel();
|
.send(Cmd::StagedVersion { reply })
|
||||||
}
|
.await
|
||||||
Self::delete_cache().await;
|
.map_err(|_| anyhow::anyhow!("updater stopped"))?;
|
||||||
|
Ok(reply_rx.await.unwrap_or(None))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl SilentUpdater {
|
impl SilentUpdater {
|
||||||
async fn check_and_download(&self, app_handle: &tauri::AppHandle) -> Result<()> {
|
/// The actor's supervisor: one `serve` epoch at a time. A panic drops the epoch — its
|
||||||
// Registered before reading the switch, so `discard_pending` either cancels it or ran first.
|
/// in-flight work and any reply it still owed — but not the mailbox or the staged
|
||||||
let cancel = CancellationToken::new();
|
/// version, so the actor restarts instead of leaving updating dead for the rest of the
|
||||||
*self.background_cancel.lock() = Some(cancel.clone());
|
/// 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);
|
let auto_check = Config::verge().await.latest_arc().auto_check_update.unwrap_or(true);
|
||||||
if !auto_check {
|
if !auto_check {
|
||||||
logging!(debug, Type::System, "Silent update skipped: auto_check_update is false");
|
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...");
|
logging!(info, Type::System, "Silent updater: checking for updates...");
|
||||||
|
let update = match app_handle.updater()?.check().await {
|
||||||
let updater = app_handle.updater()?;
|
|
||||||
let update = match updater.check().await {
|
|
||||||
Ok(Some(update)) => update,
|
Ok(Some(update)) => update,
|
||||||
Ok(None) => {
|
Ok(None) => {
|
||||||
logging!(info, Type::System, "Silent updater: no update available");
|
logging!(info, Type::System, "Silent updater: no update available");
|
||||||
return Ok(());
|
return Ok(None);
|
||||||
}
|
}
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
logging!(warn, Type::System, "Silent updater: check failed: {e}");
|
logging!(warn, Type::System, "Silent updater: check failed: {e}");
|
||||||
@@ -387,70 +505,138 @@ impl SilentUpdater {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
let version = update.version.as_str();
|
let version = update.version.clone();
|
||||||
logging!(info, Type::System, "Silent updater: update available: v{version}");
|
logging!(info, Type::System, "Silent updater: update available: v{version}");
|
||||||
|
if Self::staged_bytes(&update).await.is_some() {
|
||||||
let download_guard = self.download_lock.lock().await;
|
logging!(info, Type::System, "Silent updater: v{version} already staged");
|
||||||
// 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 {
|
} else {
|
||||||
logging!(info, Type::System, "Silent updater: downloading v{version}...");
|
logging!(info, Type::System, "Silent updater: downloading v{version}...");
|
||||||
let downloaded = tokio::select! {
|
let bytes = download(&update, |_| {}).await?;
|
||||||
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?;
|
|
||||||
logging!(info, Type::System, "Silent updater: download complete");
|
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);
|
Ok(Some(version))
|
||||||
|
|
||||||
// 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!(
|
/// One dialog install from prepare to install; every exit path answers `reply`.
|
||||||
info,
|
async fn run_install(
|
||||||
Type::System,
|
app_handle: &tauri::AppHandle,
|
||||||
"Silent updater: v{version} ready to install from the update dialog"
|
version: &str,
|
||||||
);
|
on_event: Box<dyn Fn(DownloadEvent) + Send + Sync>,
|
||||||
Ok(())
|
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));
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn start_background_check(&self, app_handle: tauri::AppHandle) {
|
/// The cancellable prepare phase: check, version filter, staged reuse or download. A
|
||||||
// Permanent watcher: daily update cycles for the lifetime of the app.
|
/// second install is declined in place; a cancel drops the work.
|
||||||
logging!(info, Type::System, "Silent updater: background task started");
|
async fn prepare_cancellable(
|
||||||
|
app_handle: &tauri::AppHandle,
|
||||||
tokio::time::sleep(std::time::Duration::from_secs(10)).await;
|
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 {
|
loop {
|
||||||
if let Err(e) = self.check_and_download(&app_handle).await {
|
let maybe = tokio::select! {
|
||||||
logging!(warn, Type::System, "Silent updater: cycle error: {e}");
|
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),
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
tokio::time::sleep(std::time::Duration::from_secs(24 * 60 * 60)).await;
|
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")));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -6,10 +6,7 @@ use crate::{
|
|||||||
snapshot::{capture_config_files, restore_files},
|
snapshot::{capture_config_files, restore_files},
|
||||||
},
|
},
|
||||||
core::auto_backup::AutoBackupManager,
|
core::auto_backup::AutoBackupManager,
|
||||||
core::{
|
core::{CoreManager, autostart, hotkey, lightweight, logger, manager::ConfigUpdateGuard, proxy_control, tray},
|
||||||
CoreManager, SilentUpdater, autostart, hotkey, lightweight, logger, manager::ConfigUpdateGuard, proxy_control,
|
|
||||||
tray,
|
|
||||||
},
|
|
||||||
};
|
};
|
||||||
use anyhow::Result;
|
use anyhow::Result;
|
||||||
use clash_verge_draft::DraftTransaction;
|
use clash_verge_draft::DraftTransaction;
|
||||||
@@ -162,10 +159,7 @@ pub(super) async fn apply(config_write: &MutexGuard<'_, ()>, patch: Patch<'_>, e
|
|||||||
}
|
}
|
||||||
transaction.commit();
|
transaction.commit();
|
||||||
match patch {
|
match patch {
|
||||||
Patch::Verge { patch, .. } => {
|
Patch::Verge { .. } => {
|
||||||
if patch.auto_check_update == Some(false) {
|
|
||||||
SilentUpdater::global().discard_pending().await;
|
|
||||||
}
|
|
||||||
if effects.contains(&Effect::ClashConfig) {
|
if effects.contains(&Effect::ClashConfig) {
|
||||||
announce(Refresh::Clash);
|
announce(Refresh::Clash);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -20,6 +20,7 @@ pub fn builder() -> tauri_specta::Builder<tauri::Wry> {
|
|||||||
cmd::restart_app,
|
cmd::restart_app,
|
||||||
cmd::install_update,
|
cmd::install_update,
|
||||||
cmd::cancel_update_download,
|
cmd::cancel_update_download,
|
||||||
|
cmd::get_staged_update,
|
||||||
cmd::restart_core,
|
cmd::restart_core,
|
||||||
cmd::upgrade_clash_core,
|
cmd::upgrade_clash_core,
|
||||||
cmd::get_runtime_state,
|
cmd::get_runtime_state,
|
||||||
|
|||||||
@@ -159,11 +159,7 @@ fn init_silent_updater() {
|
|||||||
|
|
||||||
logging!(debug, Type::Setup, "Initializing silent updater...");
|
logging!(debug, Type::Setup, "Initializing silent updater...");
|
||||||
|
|
||||||
let app_handle = Handle::app_handle();
|
SilentUpdater::start(Handle::app_handle().clone());
|
||||||
let app_handle = app_handle.clone();
|
|
||||||
tokio::spawn(async move {
|
|
||||||
SilentUpdater::global().start_background_check(app_handle).await;
|
|
||||||
});
|
|
||||||
|
|
||||||
logging!(info, Type::Setup, "Silent updater initialized");
|
logging!(info, Type::Setup, "Silent updater initialized");
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,8 +1,11 @@
|
|||||||
import { Button } from '@mui/material'
|
import { Button } from '@mui/material'
|
||||||
|
import { useLockFn } from 'ahooks'
|
||||||
import { useRef } from 'react'
|
import { useRef } from 'react'
|
||||||
|
|
||||||
import { DialogRef } from '@/components/base'
|
import { DialogRef } from '@/components/base'
|
||||||
import { useUpdate } from '@/hooks/use-update'
|
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'
|
import { UpdateViewer } from '../setting/mods/update-viewer'
|
||||||
|
|
||||||
@@ -14,10 +17,27 @@ export const UpdateButton = (props: Props) => {
|
|||||||
const { className } = props
|
const { className } = props
|
||||||
const viewerRef = useRef<DialogRef>(null)
|
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
|
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 (
|
return (
|
||||||
<>
|
<>
|
||||||
<UpdateViewer ref={viewerRef} />
|
<UpdateViewer ref={viewerRef} />
|
||||||
@@ -27,9 +47,13 @@ export const UpdateButton = (props: Props) => {
|
|||||||
variant="contained"
|
variant="contained"
|
||||||
size="small"
|
size="small"
|
||||||
className={className}
|
className={className}
|
||||||
onClick={() => viewerRef.current?.open()}
|
onClick={
|
||||||
|
ready
|
||||||
|
? () => onRestartToUpdate(updateInfo.version)
|
||||||
|
: () => viewerRef.current?.open()
|
||||||
|
}
|
||||||
>
|
>
|
||||||
New
|
{ready ? 'Restart' : 'New'}
|
||||||
</Button>
|
</Button>
|
||||||
</>
|
</>
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import { getStagedUpdate } from '@/services/cmds'
|
||||||
import { fetchCacheData, setCacheData, useQuery } from '@/services/query-client'
|
import { fetchCacheData, setCacheData, useQuery } from '@/services/query-client'
|
||||||
import { checkForUpdate } from '@/services/update'
|
import { checkForUpdate } from '@/services/update'
|
||||||
|
|
||||||
@@ -54,10 +55,16 @@ export const useUpdate = (enabled: boolean = true) => {
|
|||||||
refetchOnReconnect: false,
|
refetchOnReconnect: false,
|
||||||
})
|
})
|
||||||
|
|
||||||
|
const { data: stagedVersion } = useQuery({
|
||||||
|
queryKey: ['getStagedUpdate'],
|
||||||
|
queryFn: () => getStagedUpdate(),
|
||||||
|
})
|
||||||
|
|
||||||
return {
|
return {
|
||||||
updateInfo,
|
updateInfo,
|
||||||
checkUpdate,
|
checkUpdate,
|
||||||
loading: isValidating,
|
loading: isValidating,
|
||||||
lastCheckUpdate: lastCheckUpdate ?? null,
|
lastCheckUpdate: lastCheckUpdate ?? null,
|
||||||
|
stagedVersion: stagedVersion ?? null,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -32,6 +32,7 @@ export const commands = {
|
|||||||
onEvent,
|
onEvent,
|
||||||
}),
|
}),
|
||||||
cancelUpdateDownload: () => __TAURI_INVOKE<void>('cancel_update_download'),
|
cancelUpdateDownload: () => __TAURI_INVOKE<void>('cancel_update_download'),
|
||||||
|
getStagedUpdate: () => __TAURI_INVOKE<string | null>('get_staged_update'),
|
||||||
restartCore: () => __TAURI_INVOKE<null>('restart_core'),
|
restartCore: () => __TAURI_INVOKE<null>('restart_core'),
|
||||||
/** Replaces the managed core binary atomically instead of letting mihomo overwrite itself. */
|
/** Replaces the managed core binary atomically instead of letting mihomo overwrite itself. */
|
||||||
upgradeClashCore: (force: boolean) =>
|
upgradeClashCore: (force: boolean) =>
|
||||||
@@ -1141,6 +1142,7 @@ export type VergeEventPayloads_Deserialize = {
|
|||||||
'profile-update-completed': ProfileUpdatePayload
|
'profile-update-completed': ProfileUpdatePayload
|
||||||
'verge://run-state-changed': RunStateView_Deserialize
|
'verge://run-state-changed': RunStateView_Deserialize
|
||||||
'verge://pending-failures-changed': null
|
'verge://pending-failures-changed': null
|
||||||
|
'verge://staged-update-changed': null
|
||||||
}
|
}
|
||||||
|
|
||||||
export type VergeEventPayloads_Serialize = {
|
export type VergeEventPayloads_Serialize = {
|
||||||
@@ -1155,6 +1157,7 @@ export type VergeEventPayloads_Serialize = {
|
|||||||
'profile-update-completed': ProfileUpdatePayload
|
'profile-update-completed': ProfileUpdatePayload
|
||||||
'verge://run-state-changed': RunStateView_Serialize
|
'verge://run-state-changed': RunStateView_Serialize
|
||||||
'verge://pending-failures-changed': null
|
'verge://pending-failures-changed': null
|
||||||
|
'verge://staged-update-changed': null
|
||||||
}
|
}
|
||||||
|
|
||||||
export type WebDavFile = {
|
export type WebDavFile = {
|
||||||
|
|||||||
@@ -81,6 +81,8 @@ export const createEventBus = (deps: BusHandlerDeps) => {
|
|||||||
if (payload.mode !== 'NotRunning') forgetShownStartupError()
|
if (payload.mode !== 'NotRunning') forgetShownStartupError()
|
||||||
},
|
},
|
||||||
'verge://pending-failures-changed': () => deps.readPendingFailures(),
|
'verge://pending-failures-changed': () => deps.readPendingFailures(),
|
||||||
|
'verge://staged-update-changed': () =>
|
||||||
|
deps.revalidateKeys(['getStagedUpdate']),
|
||||||
[TEST_ALL_EVENT]: () => deps.dispatch({ type: 'testAll/requested' }),
|
[TEST_ALL_EVENT]: () => deps.dispatch({ type: 'testAll/requested' }),
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -306,6 +306,10 @@ export async function cancelUpdateDownload() {
|
|||||||
return commands.cancelUpdateDownload()
|
return commands.cancelUpdateDownload()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export async function getStagedUpdate() {
|
||||||
|
return commands.getStagedUpdate()
|
||||||
|
}
|
||||||
|
|
||||||
export async function getAppDir() {
|
export async function getAppDir() {
|
||||||
return commands.getAppDir()
|
return commands.getAppDir()
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user