From 6f6671c1e8e09330cac0c74791c4cb61e38737de Mon Sep 17 00:00:00 2001 From: Jason Date: Thu, 12 Nov 2026 19:56:13 -0800 Subject: [PATCH] feat(updater): download updates in the background and ask before installing Add an opt-in "Auto-download updates" switch to Settings > About (off by default, stored per device as autoUpdateEnabled). When it is on, CC Switch checks one minute after launch and then every six hours, downloads and verifies the new version in the background, and shows a small prompt in the bottom-right corner of the main content area asking whether to install now. Installing restarts CC Switch, which cuts requests going through the local route, so it never happens without the user's click; the prompt says so when the route is in use. The tray menu and tray panel also get a "Restart to update to vX" entry. The downloaded package is kept in a process-level cache in Rust (app_update::PENDING), not in React state: lightweight mode destroys the main window, and the download must survive that. It lives in memory only. - install_update_and_restart checks again first and reuses the cached bytes when the version matches; offline it falls back to the cached package; if the server no longer offers an update the cache is dropped and the prompt and tray entry are withdrawn (app-update-ready with null). - The cache is copied, never taken, so a failed install can be retried. - The prompt, About page and tray share one install lock. begin_install uses an explicit if: then_some would build the guard eagerly and its Drop would release a lock held by another entry point. - Portable builds and Linux installs other than AppImage cannot self-install; the switch is disabled there with the reason. Debug builds skip the background loop because dev shares settings.json with the release app. - "Later" hides the prompt for that version only; the settings dot, the About button and the tray entry still offer the install. Tested: new unit tests for the install lock, the tray item, the prompt and UpdateContext (a downloaded package counts as an update when the online check fails; rechecks run once per version). End to end on macOS with a 4.0.30 build in a sandboxed HOME: the switch downloaded and verified 4.0.31 in about 9 s, the prompt, tray entry and "Later" behaved as intended, and installing from the cache restarted into 4.0.31. --- src-tauri/src/app_update.rs | 262 ++++++++++++++++++ src-tauri/src/commands/misc.rs | 7 +- src-tauri/src/commands/settings.rs | 115 +++++--- src-tauri/src/lib.rs | 6 + src-tauri/src/settings.rs | 4 + src-tauri/src/tray.rs | 72 ++++- src/App.tsx | 2 + src/components/AutoUpdatePrompt.tsx | 128 +++++++++ src/components/settings/AboutSection.tsx | 67 ++++- src/components/settings/SettingsPage.tsx | 8 +- src/contexts/UpdateContext.tsx | 87 +++++- src/i18n/locales/de.json | 11 + src/i18n/locales/en.json | 11 + src/i18n/locales/ja.json | 11 + src/i18n/locales/ko.json | 11 + src/i18n/locales/ru.json | 11 + src/i18n/locales/tr.json | 11 + src/i18n/locales/zh-TW.json | 11 + src/i18n/locales/zh.json | 11 + src/lib/api/settings.ts | 10 + src/lib/updater.ts | 19 ++ src/tray-panel/TrayPanel.tsx | 17 ++ src/tray-panel/api.ts | 2 + src/types.ts | 2 + tests/components/AutoUpdatePrompt.test.tsx | 83 ++++++ .../UpdateContext.autoUpdate.test.tsx | 89 ++++++ 26 files changed, 1014 insertions(+), 54 deletions(-) create mode 100644 src-tauri/src/app_update.rs create mode 100644 src/components/AutoUpdatePrompt.tsx create mode 100644 tests/components/AutoUpdatePrompt.test.tsx create mode 100644 tests/contexts/UpdateContext.autoUpdate.test.tsx diff --git a/src-tauri/src/app_update.rs b/src-tauri/src/app_update.rs new file mode 100644 index 000000000..92196cc4d --- /dev/null +++ b/src-tauri/src/app_update.rs @@ -0,0 +1,262 @@ +//! 应用自动更新:开关打开后在后台下载新版本,装不装由用户确认。 +//! +//! 下载好的安装包放在进程级缓存里,不放在前端:轻量模式会销毁主窗口,React 状态跟着没了, +//! 后台下好的包不能跟着丢。主窗口重建后用 [`status`] 取回「已下载、待安装」。 +//! +//! 只缓存在内存里(十几 MB),不落盘:落盘的包下次启动要重新验签、还要处理残留,换来的只是 +//! 退出后不用再下一次,不值。 + +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::Mutex; +use std::time::Duration; + +use serde::Serialize; +use tauri::{AppHandle, Emitter}; +use tauri_plugin_updater::{Update, Updater, UpdaterExt}; + +/// 待安装的版本变了就发给前端:载荷是 `Option`,`null` 表示缓存作废了 +/// (版本被撤回),提示要收起。 +pub const UPDATE_READY_EVENT: &str = "app-update-ready"; + +/// 启动后第一次检查的延迟:避开启动时的接管、导入等重活。 +const FIRST_CHECK_DELAY: Duration = Duration::from_secs(60); +/// CC Switch 常驻托盘,一挂就是几天;只在启动时查一次,这个开关就形同虚设。 +const CHECK_INTERVAL: Duration = Duration::from_secs(6 * 60 * 60); + +struct PendingUpdate { + update: Update, + bytes: Vec, +} + +static PENDING: Mutex> = Mutex::new(None); +static DOWNLOADING: AtomicBool = AtomicBool::new(false); +/// 弹窗、关于页、托盘三个入口共用:同一时间只能有一次安装(安装会替换应用、做退出清理)。 +static INSTALLING: AtomicBool = AtomicBool::new(false); + +#[derive(Debug, Clone, Serialize, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct ReadyUpdate { + pub version: String, + pub notes: Option, +} + +#[derive(Debug, Clone, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct AutoUpdateStatus { + /// 这台机器能不能自动安装(便携版、Linux 非 AppImage 不行)。 + pub supported: bool, + pub downloading: bool, + /// 已下载、待安装的版本。开关关着时不报(关掉即视为不要了)。 + pub ready: Option, + /// 有应用在用路由服务:重启会切断进行中的请求,安装提示里要写明。 + pub routing_in_use: bool, +} + +/// 便携版:可执行文件旁边有 `portable.ini`。便携版没有安装器,只能去下载页手动换。 +pub fn is_portable() -> bool { + std::env::current_exe() + .ok() + .and_then(|exe| exe.parent().map(|dir| dir.join("portable.ini").is_file())) + .unwrap_or(false) +} + +/// Tauri updater 在 Linux 上只会替换 AppImage;deb / rpm 装的版本由系统包管理器管。 +#[cfg(target_os = "linux")] +fn platform_supports_self_install() -> bool { + std::env::var_os("APPIMAGE").is_some() +} + +#[cfg(not(target_os = "linux"))] +fn platform_supports_self_install() -> bool { + true +} + +pub fn auto_install_supported() -> bool { + !is_portable() && platform_supports_self_install() +} + +fn enabled() -> bool { + crate::settings::get_settings().auto_update_enabled +} + +fn pending_guard() -> std::sync::MutexGuard<'static, Option> { + PENDING.lock().unwrap_or_else(|e| e.into_inner()) +} + +/// 已下载、待安装的版本;开关关着时视为没有。 +pub fn ready() -> Option { + if !enabled() { + return None; + } + pending_guard().as_ref().map(|pending| ReadyUpdate { + version: pending.update.version.clone(), + notes: pending.update.body.clone(), + }) +} + +pub fn status(routing_in_use: bool) -> AutoUpdateStatus { + AutoUpdateStatus { + supported: auto_install_supported(), + downloading: DOWNLOADING.load(Ordering::SeqCst), + ready: ready(), + routing_in_use, + } +} + +/// 缓存里这个版本的安装包(复制一份)。不从缓存取走:安装失败时还能再装,离线也能重试; +/// 安装成功进程就退出了,缓存不用清。 +pub fn pending_bytes_for(version: &str) -> Option> { + pending_guard() + .as_ref() + .filter(|pending| pending.update.version == version) + .map(|pending| pending.bytes.clone()) +} + +/// 离线时的退路:检查不了更新,就装已经下好的那个版本(同样只复制、不取走)。 +pub fn any_pending() -> Option<(Update, Vec)> { + pending_guard() + .as_ref() + .map(|pending| (pending.update.clone(), pending.bytes.clone())) +} + +/// 缓存作废(服务器上已经没有这个版本了):清掉,并让前端提示和托盘入口一起收起。 +pub fn discard_pending(app: &AppHandle) { + if pending_guard().take().is_some() { + log::info!("已下载的应用更新不再可用,已丢弃"); + let _ = app.emit(UPDATE_READY_EVENT, None::); + crate::tray::refresh_tray_menu(app); + } +} + +/// 安装期间持有;安装失败返回时随 drop 释放,成功时进程直接退出 / 重启。 +pub struct InstallGuard; + +impl Drop for InstallGuard { + fn drop(&mut self) { + INSTALLING.store(false, Ordering::SeqCst); + } +} + +pub fn is_installing() -> bool { + INSTALLING.load(Ordering::SeqCst) +} + +/// 拿到安装权;已经有一次安装在跑就返回 `None`。 +pub fn begin_install() -> Option { + // 不能写 `then_some(InstallGuard)`:守卫会先构造出来,拿不到安装权时随即 drop, + // 反而把别人持有的锁清掉。 + if INSTALLING.swap(true, Ordering::SeqCst) { + None + } else { + Some(InstallGuard) + } +} + +pub fn build_updater(app: &AppHandle) -> Result { + let builder = app.updater_builder(); + // Windows 上 updater 以 `msiexec /passive /promptrestart` 安装 MSI。passive 没有模态框、 + // 未指定重启选项时,安装目录里有文件被占用,Windows Installer 会不经确认直接重启系统 + // (#8534)。`/promptrestart` 只对应 REBOOTPROMPT,挡不住这一点,因此显式追加 + // REBOOT=ReallySuppress(即 `/norestart`)。旧版本的 updater 不带这个参数, + // 由 MSI 模板自身的 REBOOT 属性兜底。 + #[cfg(target_os = "windows")] + let builder = builder.installer_arg("REBOOT=ReallySuppress"); + builder + .build() + .map_err(|e| format!("初始化更新器失败: {e}")) +} + +struct DownloadingFlag; + +impl Drop for DownloadingFlag { + fn drop(&mut self) { + DOWNLOADING.store(false, Ordering::SeqCst); + } +} + +/// 检查并下载最新版本,放进缓存,然后通知前端和托盘。已经下好同一版本就直接返回。 +/// 同时只跑一份:正在下载时再调用,返回当前缓存(可能为空)。 +pub async fn download_latest(app: &AppHandle) -> Result, String> { + if DOWNLOADING.swap(true, Ordering::SeqCst) { + return Ok(ready()); + } + let _flag = DownloadingFlag; + + let Some(update) = build_updater(app)? + .check() + .await + .map_err(|e| format!("检查更新失败: {e}"))? + else { + // 已是最新(或缓存的版本被撤回了):缓存的包不能再装。 + discard_pending(app); + return Ok(None); + }; + + let cached_same_version = pending_guard() + .as_ref() + .is_some_and(|pending| pending.update.version == update.version); + if cached_same_version { + return Ok(ready()); + } + + log::info!("后台下载应用更新: {}", update.version); + // download() 内部会校验签名,拿到字节即说明包可信。 + let bytes = update + .download(|_, _| {}, || {}) + .await + .map_err(|e| format!("下载更新失败: {e}"))?; + log::info!("应用更新已下载,等待用户确认安装: {}", update.version); + + let ready_update = ReadyUpdate { + version: update.version.clone(), + notes: update.body.clone(), + }; + *pending_guard() = Some(PendingUpdate { update, bytes }); + + let _ = app.emit(UPDATE_READY_EVENT, Some(&ready_update)); + crate::tray::refresh_tray_menu(app); + Ok(Some(ready_update)) +} + +/// 开关打开时,启动一分钟后检查一次,之后每 6 小时一次。 +/// +/// 开发构建不跑:dev 和正式版共用 `~/.cc-switch/settings.json`,开着开关的话每次 `pnpm dev` +/// 都会下一遍正式安装包,而 dev 二进制根本装不了。需要时在关于页手动触发。 +pub fn spawn_background_loop(app: AppHandle) { + if cfg!(debug_assertions) { + return; + } + tauri::async_runtime::spawn(async move { + tokio::time::sleep(FIRST_CHECK_DELAY).await; + loop { + if enabled() && auto_install_supported() { + if let Err(e) = download_latest(&app).await { + log::warn!("自动更新下载失败: {e}"); + } + } + tokio::time::sleep(CHECK_INTERVAL).await; + } + }); +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn only_one_install_runs_at_a_time_and_failure_releases_it() { + let first = begin_install().expect("first install gets the slot"); + assert!(is_installing()); + assert!(begin_install().is_none(), "second entry point is refused"); + // 被拒的那次不能顺手把锁放掉,第三个入口照样要被拒 + assert!(is_installing()); + assert!( + begin_install().is_none(), + "third entry point is refused too" + ); + drop(first); // 安装失败返回 + assert!(!is_installing()); + let again = begin_install(); + assert!(again.is_some()); + } +} diff --git a/src-tauri/src/commands/misc.rs b/src-tauri/src/commands/misc.rs index 27bb6c3e7..c752d458a 100644 --- a/src-tauri/src/commands/misc.rs +++ b/src-tauri/src/commands/misc.rs @@ -126,12 +126,7 @@ pub async fn open_portable_update_download( /// 判断是否为便携版(绿色版)运行 #[tauri::command] pub async fn is_portable_mode() -> Result { - let exe_path = std::env::current_exe().map_err(|e| format!("获取可执行路径失败: {e}"))?; - if let Some(dir) = exe_path.parent() { - Ok(dir.join("portable.ini").is_file()) - } else { - Ok(false) - } + Ok(crate::app_update::is_portable()) } /// 获取应用启动阶段的初始化错误(若有)。 diff --git a/src-tauri/src/commands/settings.rs b/src-tauri/src/commands/settings.rs index 3d2589946..171f239c2 100644 --- a/src-tauri/src/commands/settings.rs +++ b/src-tauri/src/commands/settings.rs @@ -339,51 +339,69 @@ pub async fn restart_app(app: AppHandle) -> Result { /// 下载并安装应用更新,然后由后端直接重启应用。 /// -/// macOS 更新会原地替换 `.app` bundle。如果先返回前端、再让旧 WebView 调 -/// `process.relaunch()`,旧进程可能已经处在 bundle 被替换后的不稳定窗口期。 -/// 这里把退出清理、安装和重启串在同一个后端流程中,避免依赖旧前端继续执行。 +/// 自动更新已经在后台下好同一版本时直接用缓存的包(见 `app_update`);检查更新失败 +/// (离线)但手里有下好的包,也装那个包。 #[tauri::command] pub async fn install_update_and_restart(app: AppHandle) -> Result { - let builder = app.updater_builder(); - // Windows 上 updater 以 `msiexec /passive /promptrestart` 安装 MSI。passive 没有模态框、 - // 未指定重启选项时,安装目录里有文件被占用,Windows Installer 会不经确认直接重启系统 - // (#8534)。`/promptrestart` 只对应 REBOOTPROMPT,挡不住这一点,因此显式追加 - // REBOOT=ReallySuppress(即 `/norestart`)。旧版本的 updater 不带这个参数, - // 由 MSI 模板自身的 REBOOT 属性兜底。 - #[cfg(target_os = "windows")] - let builder = builder.installer_arg("REBOOT=ReallySuppress"); - let updater = builder - .build() - .map_err(|e| format!("初始化更新器失败: {e}"))?; - - let Some(update) = updater - .check() - .await - .map_err(|e| format!("检查更新失败: {e}"))? - else { + // 弹窗、关于页、托盘可能先后点了安装:第二次直接拒绝,避免两次安装同时替换应用、做退出清理 + let Some(_installing) = crate::app_update::begin_install() else { + return Err("正在安装更新,请稍候".to_string()); + }; + let checked = match crate::app_update::build_updater(&app)?.check().await { + Ok(update) => update, + Err(e) => { + if let Some((update, bytes)) = crate::app_update::any_pending() { + log::warn!("检查更新失败({e}),改装已下载的 {}", update.version); + return install_and_restart(app, update, bytes).await; + } + return Err(format!("检查更新失败: {e}")); + } + }; + let Some(update) = checked else { + // 已是最新(下好的版本被撤回了):缓存的包不能再装,提示和托盘入口一起收起 + crate::app_update::discard_pending(&app); return Ok(false); }; - log::info!("开始下载应用更新: {}", update.version); - let progress_handle = app.clone(); - let mut downloaded: u64 = 0; - let bytes = update - .download( - move |chunk_len, content_len| { - downloaded = downloaded.saturating_add(chunk_len as u64); - let _ = progress_handle.emit( - "update-download-progress", - UpdateDownloadProgress { - downloaded, - total: content_len, + let bytes = match crate::app_update::pending_bytes_for(&update.version) { + Some(bytes) => { + log::info!("使用已下载的应用更新: {}", update.version); + bytes + } + None => { + log::info!("开始下载应用更新: {}", update.version); + let progress_handle = app.clone(); + let mut downloaded: u64 = 0; + update + .download( + move |chunk_len, content_len| { + downloaded = downloaded.saturating_add(chunk_len as u64); + let _ = progress_handle.emit( + "update-download-progress", + UpdateDownloadProgress { + downloaded, + total: content_len, + }, + ); }, - ); - }, - || {}, - ) - .await - .map_err(|e| format!("下载更新失败: {e}"))?; + || {}, + ) + .await + .map_err(|e| format!("下载更新失败: {e}"))? + } + }; + install_and_restart(app, update, bytes).await +} + +/// macOS 更新会原地替换 `.app` bundle。如果先返回前端、再让旧 WebView 调 +/// `process.relaunch()`,旧进程可能已经处在 bundle 被替换后的不稳定窗口期。 +/// 这里把退出清理、安装和重启串在同一个后端流程中,避免依赖旧前端继续执行。 +async fn install_and_restart( + app: AppHandle, + update: tauri_plugin_updater::Update, + bytes: Vec, +) -> Result { log::info!("开始安装应用更新: {}", update.version); #[cfg(target_os = "windows")] @@ -421,6 +439,27 @@ pub async fn install_update_and_restart(app: AppHandle) -> Result } } +/// 自动更新的状态:能不能自动安装、是否在下载、已下好待装的版本。 +#[tauri::command] +pub async fn get_auto_update_status( + state: tauri::State<'_, crate::store::AppState>, +) -> Result { + Ok(crate::app_update::status(crate::tray::routing_in_use( + state.inner(), + ))) +} + +/// 立刻在后台检查并下载最新版本(打开自动更新开关时调用)。不支持自动安装的机器直接返回空。 +#[tauri::command] +pub async fn download_app_update( + app: AppHandle, +) -> Result, String> { + if !crate::app_update::auto_install_supported() { + return Ok(None); + } + crate::app_update::download_latest(&app).await +} + /// 检查是否有可用的应用更新,返回可用的新版本号(无更新时返回 None)。 /// /// 数据库版本过新的恢复界面用它判断:升级应用能否解决问题。若返回 None,说明 diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 0c6123ee7..8cbf2857f 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -3,6 +3,7 @@ mod agy_config; mod agy_smoke_tests; mod app_config; mod app_store; +mod app_update; mod auto_launch; mod claude_desktop_config; mod claude_mcp; @@ -1434,6 +1435,9 @@ pub fn run() { } } + // 自动更新:开关打开时后台定时检查并下载新版本(装不装由用户确认) + crate::app_update::spawn_background_loop(app.handle().clone()); + // 异常退出恢复 + 代理状态自动恢复 let app_handle = app.handle().clone(); tauri::async_runtime::spawn(async move { @@ -1657,6 +1661,8 @@ pub fn run() { commands::set_log_config, commands::restart_app, commands::install_update_and_restart, + commands::get_auto_update_status, + commands::download_app_update, commands::check_app_update_available, commands::check_for_updates, commands::open_portable_update_download, diff --git a/src-tauri/src/settings.rs b/src-tauri/src/settings.rs index 3bb867bbf..eb4798864 100644 --- a/src-tauri/src/settings.rs +++ b/src-tauri/src/settings.rs @@ -534,6 +534,9 @@ pub struct AppSettings { /// many users do not want to chase every release). #[serde(default)] pub check_tool_updates_on_startup: bool, + /// 自动下载 CC Switch 新版本,下好后问用户要不要安装(默认关)。设备级,不随云同步。 + #[serde(default)] + pub auto_update_enabled: bool, /// 点托盘图标出原生菜单,不出托盘面板(macOS / Windows;Linux 只能出原生菜单,不看这一项)。 /// 默认关:用托盘面板,想要原生菜单在设置里换回。 #[serde(default)] @@ -753,6 +756,7 @@ impl Default for AppSettings { show_profile_switcher: false, show_provider_search: true, check_tool_updates_on_startup: false, + auto_update_enabled: false, native_tray_menu: false, preserve_codex_official_auth_on_switch: false, codex_quota_protection: CodexQuotaProtection::default(), diff --git a/src-tauri/src/tray.rs b/src-tauri/src/tray.rs index b1153b37a..3c210fe20 100644 --- a/src-tauri/src/tray.rs +++ b/src-tauri/src/tray.rs @@ -93,6 +93,8 @@ pub struct TrayTexts { pub quit: &'static str, /// 有应用在用路由服务时的「退出」:写明后果(客户端指回直连、路由服务停止,下次打开自动接回)。 pub quit_stops_routing: &'static str, + /// 自动更新已下好新版本时的菜单项:`{version}` + pub install_update: &'static str, pub projects_label: &'static str, pub no_project_label: &'static str, pub header_direct: &'static str, @@ -206,6 +208,7 @@ impl TrayTexts { lightweight_mode: "Lightweight mode", quit: "Quit CC Switch", quit_stops_routing: "Quit CC Switch (stops the routing service)", + install_update: "Restart to update to v{version}", projects_label: "Projects", no_project_label: "No project", header_direct: "Direct", @@ -262,6 +265,7 @@ impl TrayTexts { lightweight_mode: "경량 모드", quit: "CC Switch 종료", quit_stops_routing: "CC Switch 종료 (라우팅 서비스 중지)", + install_update: "재시작하여 v{version}(으)로 업데이트", projects_label: "프로젝트", no_project_label: "프로젝트 없음", header_direct: "직접 연결", @@ -316,6 +320,7 @@ impl TrayTexts { lightweight_mode: "Lightweight-Modus", quit: "CC Switch beenden", quit_stops_routing: "CC Switch beenden (Routing-Dienst wird gestoppt)", + install_update: "Neu starten und auf v{version} aktualisieren", projects_label: "Projekte", no_project_label: "Kein Projekt", header_direct: "Direkt", @@ -372,6 +377,7 @@ impl TrayTexts { lightweight_mode: "Облегчённый режим", quit: "Выйти из CC Switch", quit_stops_routing: "Выйти из CC Switch (служба маршрутизации остановится)", + install_update: "Перезапустить и обновить до v{version}", projects_label: "Проекты", no_project_label: "Без проекта", header_direct: "Напрямую", @@ -426,6 +432,7 @@ impl TrayTexts { lightweight_mode: "Hafif mod", quit: "CC Switch'ten çık", quit_stops_routing: "CC Switch'ten çık (yönlendirme hizmeti durur)", + install_update: "Yeniden başlat ve v{version} sürümüne güncelle", projects_label: "Projeler", no_project_label: "Proje yok", header_direct: "Doğrudan", @@ -480,6 +487,7 @@ impl TrayTexts { lightweight_mode: "軽量モード", quit: "CC Switch を終了", quit_stops_routing: "CC Switch を終了(ルーティングサービスが停止します)", + install_update: "再起動して v{version} に更新", projects_label: "プロジェクト", no_project_label: "プロジェクトを使用しない", header_direct: "直接接続", @@ -536,6 +544,7 @@ impl TrayTexts { lightweight_mode: "輕量模式", quit: "退出 CC Switch", quit_stops_routing: "退出 CC Switch(路由服務會停止)", + install_update: "重新啟動並更新到 v{version}", projects_label: "專案", no_project_label: "不使用專案", header_direct: "直連", @@ -590,6 +599,7 @@ impl TrayTexts { lightweight_mode: "轻量模式", quit: "退出 CC Switch", quit_stops_routing: "退出 CC Switch(路由服务会停止)", + install_update: "重启并更新到 v{version}", projects_label: "项目", no_project_label: "不使用项目", header_direct: "直连", @@ -1784,6 +1794,8 @@ struct MenuStatus { problems: Vec, feedback: Option, routing_in_use: bool, + /// 自动更新已下好、待安装的版本。 + update_ready: Option, } // ─── 菜单模型(纯数据)──────────────────────────────────────────────────────── @@ -1871,6 +1883,9 @@ fn problem_text(texts: &TrayTexts, problem: &TrayProblem) -> String { } } +/// 托盘 / 面板里「重启并更新」的事件 id。 +const INSTALL_UPDATE_ID: &str = "app_update:install"; + fn problem_id(problem: &TrayProblem) -> String { match problem { TrayProblem::ServiceDown { .. } => "nav:settings:routing".to_string(), @@ -2157,6 +2172,12 @@ fn build_menu_model( // 窗口找不回来时托盘是唯一入口,「打开 CC Switch」一直放在最上面。 menu.push(TrayEntry::item("show_main", texts.show_main)); + if let Some(version) = &status.update_ready { + menu.push(TrayEntry::item( + INSTALL_UPDATE_ID, + fill(texts.install_update, &[("version", version)]), + )); + } menu.push(TrayEntry::Separator); if !apps.is_empty() { @@ -2235,6 +2256,7 @@ fn collect_status( problems, feedback: current_feedback(), routing_in_use: routing_in_use(app_state), + update_ready: crate::app_update::ready().map(|ready| ready.version), }; Ok((snapshots, status)) } @@ -2253,7 +2275,7 @@ fn collect_model(app_state: &AppState, texts: &TrayTexts) -> Result bool { +pub(crate) fn routing_in_use(app_state: &AppState) -> bool { app_state.proxy_service.running_now() == Some(true) && crate::mode::current::any_proxy() } @@ -2264,6 +2286,8 @@ fn routing_in_use(app_state: &AppState) -> bool { #[derive(Debug, Clone, Serialize)] #[serde(rename_all = "camelCase")] pub struct PanelModel { + /// 自动更新已下好新版本:点了重启安装。 + pub update: Option, pub problems: Vec, pub feedback: Option, pub apps: Vec, @@ -2539,6 +2563,10 @@ pub(crate) fn collect_panel_model(app_state: &AppState) -> Result show_main_window(app), + INSTALL_UPDATE_ID => { + // 弹窗或关于页已经在装了:这次点击什么都不做 + if crate::app_update::is_installing() { + return; + } + let app = app.clone(); + tauri::async_runtime::spawn(async move { + if let Err(e) = crate::commands::install_update_and_restart(app.clone()).await { + log::error!("托盘安装更新失败: {e}"); + // 失败原因只有主界面能说清:打开关于页,用户在那里重试会看到报错 + navigate( + &app, + TrayNavigation { + section: Some("about".to_string()), + ..Default::default() + }, + ); + } + }); + } "open_website" => { if let Err(e) = app.opener().open_url("https://ccswitch.io", None::) { log::error!("打开官方网站失败: {e}"); @@ -4579,6 +4627,27 @@ mod tests { entries.iter().map(text_of).collect() } + #[test] + fn downloaded_update_adds_install_item_right_below_open_main() { + let status = MenuStatus { + update_ready: Some("4.1.0".to_string()), + ..Default::default() + }; + let entries = build_menu_model(&zh(), &status, &[], false, now()); + let texts = texts_of(&entries); + assert_eq!(texts[0], "打开 CC Switch"); + assert_eq!(texts[1], "重启并更新到 v4.1.0"); + assert!(matches!( + &entries[1], + TrayEntry::Item { id, .. } if id == INSTALL_UPDATE_ID + )); + + let without = build_menu_model(&zh(), &MenuStatus::default(), &[], false, now()); + assert!(!without + .iter() + .any(|entry| matches!(entry, TrayEntry::Item { id, .. } if id == INSTALL_UPDATE_ID))); + } + fn children_of(menu: &[TrayEntry], app: &AppType) -> Vec { menu.iter() .find_map(|entry| match entry { @@ -5096,6 +5165,7 @@ mod tests { name: "DeepSeek".to_string(), }), routing_in_use: false, + update_ready: None, }; let menu = build_menu_model(&zh(), &status, &[], false, now()); assert_eq!( diff --git a/src/App.tsx b/src/App.tsx index 348d78bfa..1fc03d235 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -83,6 +83,7 @@ import { } from "@/lib/navigation"; import { Sidebar } from "@/components/shell/Sidebar"; import { useUpdate } from "@/contexts/UpdateContext"; +import { AutoUpdatePrompt } from "@/components/AutoUpdatePrompt"; import { NewLayoutDialog } from "@/components/shell/NewLayoutDialog"; import { AppPageHeader, @@ -1963,6 +1964,7 @@ function App() { > }>{renderContent()} + diff --git a/src/components/AutoUpdatePrompt.tsx b/src/components/AutoUpdatePrompt.tsx new file mode 100644 index 000000000..1de139b23 --- /dev/null +++ b/src/components/AutoUpdatePrompt.tsx @@ -0,0 +1,128 @@ +import { useCallback, useEffect, useState } from "react"; +import { useTranslation } from "react-i18next"; +import { Download, Loader2 } from "lucide-react"; +import { Button } from "@/components/ui/button"; +import { useUpdate } from "@/contexts/UpdateContext"; +import { settingsApi } from "@/lib/api"; +import { toast } from "@/lib/toast"; +import { extractErrorMessage } from "@/utils/errorUtils"; + +// 点了「稍后」的版本记在本机:同一版本不再弹,侧栏红点、关于页按钮和托盘菜单里仍能安装 +const DISMISSED_KEY = "ccswitch:autoUpdate:promptDismissedVersion"; +// 提示挂着时多久重取一次路由状态(本机 IPC,开销可忽略) +const ROUTING_REFRESH_MS = 5000; + +function readDismissed(): string | null { + try { + return localStorage.getItem(DISMISSED_KEY); + } catch { + return null; + } +} + +/** + * 自动更新在后台下好新版本后,主界面内容区右下角的安装提示。 + * 装不装由用户点:CC Switch 一重启,经本地路由的请求会被切断。 + */ +export function AutoUpdatePrompt() { + const { t } = useTranslation(); + const { readyUpdate, routingInUse, refreshAutoUpdate, resetDismiss } = + useUpdate(); + const [dismissedVersion, setDismissedVersion] = useState(readDismissed); + const [installing, setInstalling] = useState(false); + + const version = readyUpdate?.version; + const visible = !!version && dismissedVersion !== version; + + // 显示期间定时重取状态:用户可能在提示挂着时才开路由,「请求会中断」的警告要跟上 + useEffect(() => { + if (!visible) return; + void refreshAutoUpdate(); + const timer = window.setInterval( + () => void refreshAutoUpdate(), + ROUTING_REFRESH_MS, + ); + return () => window.clearInterval(timer); + }, [visible, refreshAutoUpdate]); + + const handleLater = useCallback(() => { + if (!version) return; + setDismissedVersion(version); + try { + localStorage.setItem(DISMISSED_KEY, version); + } catch { + // 存不下就只在本次运行里不再弹 + } + }, [version]); + + const handleInstall = useCallback(async () => { + setInstalling(true); + try { + resetDismiss(); + const installed = await settingsApi.installUpdateAndRestart(); + if (!installed) { + // 服务器上已经没有更新了(版本被撤回):后端不再报这个包,提示随之收起 + setInstalling(false); + await refreshAutoUpdate(); + } + } catch (error) { + console.error("[AutoUpdatePrompt] Install failed", error); + toast.error(t("autoUpdate.installFailed"), { + description: extractErrorMessage(error) || undefined, + closeButton: true, + }); + setInstalling(false); + } + }, [refreshAutoUpdate, resetDismiss, t]); + + if (!visible) return null; + + return ( +
+
+ +
+

+ {t("autoUpdate.readyTitle", { version })} +

+

+ {routingInUse + ? t("autoUpdate.readyBodyRouting") + : t("autoUpdate.readyBody")} +

+
+
+
+ + +
+
+ ); +} diff --git a/src/components/settings/AboutSection.tsx b/src/components/settings/AboutSection.tsx index 4b4645198..d53628f5b 100644 --- a/src/components/settings/AboutSection.tsx +++ b/src/components/settings/AboutSection.tsx @@ -15,16 +15,20 @@ import { Button } from "@/components/ui/button"; import { useTranslation } from "react-i18next"; import { toast } from "@/lib/toast"; import { getVersion } from "@tauri-apps/api/app"; -import { settingsApi } from "@/lib/api"; +import { providersApi, settingsApi } from "@/lib/api"; import { useUpdate } from "@/contexts/UpdateContext"; import { Badge } from "@/components/ui/badge"; import { WhatsNewDialog } from "@/components/WhatsNewDialog"; import { WHATS_NEW_ENTRIES, entriesUpTo } from "@/lib/whatsNew"; import ccswitchLogo from "@/assets/icons/logo.svg"; import { extractErrorMessage } from "@/utils/errorUtils"; +import { Switch } from "@/components/ui/switch"; +import { SettingsRow } from "./SettingsLayout"; interface AboutSectionProps { isPortable: boolean; + autoUpdateEnabled?: boolean; + onAutoSave?: (updates: { autoUpdateEnabled: boolean }) => Promise; } // 应用自身版本(getVersion,本地毫秒级、无网络)也缓存一份,纯为重挂时免去 loading 闪烁。 @@ -45,7 +49,11 @@ function readStarPromptDismissed(): boolean { * 设置 → 关于:版本、便携模式、检查更新 / 安装并重启、项目链接。 * 命令行应用的安装与升级在侧栏「应用」页。 */ -export function AboutSection({ isPortable }: AboutSectionProps) { +export function AboutSection({ + isPortable, + autoUpdateEnabled = false, + onAutoSave, +}: AboutSectionProps) { const { t } = useTranslation(); // 惰性初始化自模块缓存:重挂时首帧即渲染上次的值,避免 loading 闪烁;首次挂载缓存 // 为空则回退到原始初值(null / loading)。 @@ -63,8 +71,35 @@ export function AboutSection({ isPortable }: AboutSectionProps) { [version], ); - const { hasUpdate, updateInfo, checkUpdate, resetDismiss, isChecking } = - useUpdate(); + const { + hasUpdate, + updateInfo, + checkUpdate, + resetDismiss, + isChecking, + autoUpdateSupported, + refreshAutoUpdate, + } = useUpdate(); + + const handleAutoUpdateChange = useCallback( + async (enabled: boolean) => { + if (!onAutoSave) return; + const saved = await onAutoSave({ autoUpdateEnabled: enabled }); + if (!saved) return; + // 关掉即视为不要已下好的包(后端不再报),打开就马上在后台下一次 + await refreshAutoUpdate(); + // 托盘里的「重启并更新」跟着开关出现 / 消失 + providersApi.updateTrayMenu().catch(console.error); + if (enabled) { + settingsApi + .downloadAppUpdate() + .catch((error) => + console.error("[AboutSection] Auto update download failed", error), + ); + } + }, + [onAutoSave, refreshAutoUpdate], + ); useEffect(() => { let active = true; @@ -271,6 +306,30 @@ export function AboutSection({ isPortable }: AboutSectionProps) { )} + {onAutoSave && ( + // 关于页的其它行是 px-5,这里用 SettingsRow 对齐(SettingsSwitchRow 固定 px-4) + void handleAutoUpdateChange(value)} + aria-label={t("autoUpdate.toggle")} + /> + } + /> + )} +
{starPromptDismissed && (
)} + {state?.update && ( + + )} {state?.problems.map((problem) => (