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.
This commit is contained in:
Jason
2026-11-12 19:56:13 -08:00
parent 24eb40c695
commit 6f6671c1e8
26 changed files with 1014 additions and 54 deletions
+262
View File
@@ -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<ReadyUpdate>`,`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<u8>,
}
static PENDING: Mutex<Option<PendingUpdate>> = 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<String>,
}
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AutoUpdateStatus {
/// 这台机器能不能自动安装(便携版、Linux 非 AppImage 不行)。
pub supported: bool,
pub downloading: bool,
/// 已下载、待安装的版本。开关关着时不报(关掉即视为不要了)。
pub ready: Option<ReadyUpdate>,
/// 有应用在用路由服务:重启会切断进行中的请求,安装提示里要写明。
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<PendingUpdate>> {
PENDING.lock().unwrap_or_else(|e| e.into_inner())
}
/// 已下载、待安装的版本;开关关着时视为没有。
pub fn ready() -> Option<ReadyUpdate> {
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<Vec<u8>> {
pending_guard()
.as_ref()
.filter(|pending| pending.update.version == version)
.map(|pending| pending.bytes.clone())
}
/// 离线时的退路:检查不了更新,就装已经下好的那个版本(同样只复制、不取走)。
pub fn any_pending() -> Option<(Update, Vec<u8>)> {
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::<ReadyUpdate>);
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<InstallGuard> {
// 不能写 `then_some(InstallGuard)`:守卫会先构造出来,拿不到安装权时随即 drop,
// 反而把别人持有的锁清掉。
if INSTALLING.swap(true, Ordering::SeqCst) {
None
} else {
Some(InstallGuard)
}
}
pub fn build_updater(app: &AppHandle) -> Result<Updater, String> {
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<Option<ReadyUpdate>, 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());
}
}
+1 -6
View File
@@ -126,12 +126,7 @@ pub async fn open_portable_update_download(
/// 判断是否为便携版(绿色版)运行
#[tauri::command]
pub async fn is_portable_mode() -> Result<bool, String> {
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())
}
/// 获取应用启动阶段的初始化错误(若有)。
+77 -38
View File
@@ -339,51 +339,69 @@ pub async fn restart_app(app: AppHandle) -> Result<bool, String> {
/// 下载并安装应用更新,然后由后端直接重启应用。
///
/// macOS 更新会原地替换 `.app` bundle。如果先返回前端、再让旧 WebView 调
/// `process.relaunch()`,旧进程可能已经处在 bundle 被替换后的不稳定窗口期。
/// 这里把退出清理、安装和重启串在同一个后端流程中,避免依赖旧前端继续执行。
/// 自动更新已经在后台下好同一版本时直接用缓存的包(见 `app_update`);检查更新失败
/// (离线)但手里有下好的包,也装那个包。
#[tauri::command]
pub async fn install_update_and_restart(app: AppHandle) -> Result<bool, String> {
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<u8>,
) -> Result<bool, String> {
log::info!("开始安装应用更新: {}", update.version);
#[cfg(target_os = "windows")]
@@ -421,6 +439,27 @@ pub async fn install_update_and_restart(app: AppHandle) -> Result<bool, String>
}
}
/// 自动更新的状态:能不能自动安装、是否在下载、已下好待装的版本。
#[tauri::command]
pub async fn get_auto_update_status(
state: tauri::State<'_, crate::store::AppState>,
) -> Result<crate::app_update::AutoUpdateStatus, String> {
Ok(crate::app_update::status(crate::tray::routing_in_use(
state.inner(),
)))
}
/// 立刻在后台检查并下载最新版本(打开自动更新开关时调用)。不支持自动安装的机器直接返回空。
#[tauri::command]
pub async fn download_app_update(
app: AppHandle,
) -> Result<Option<crate::app_update::ReadyUpdate>, String> {
if !crate::app_update::auto_install_supported() {
return Ok(None);
}
crate::app_update::download_latest(&app).await
}
/// 检查是否有可用的应用更新,返回可用的新版本号(无更新时返回 None)。
///
/// 数据库版本过新的恢复界面用它判断:升级应用能否解决问题。若返回 None,说明
+6
View File
@@ -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,
+4
View File
@@ -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(),
+71 -1
View File
@@ -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<TrayProblem>,
feedback: Option<TrayFeedback>,
routing_in_use: bool,
/// 自动更新已下好、待安装的版本。
update_ready: Option<String>,
}
// ─── 菜单模型(纯数据)────────────────────────────────────────────────────────
@@ -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<TrayModel, A
/// 退出会让它们断开的情况:路由服务在跑,且有应用在路由 / 聚合模式(含 Claude Desktop;和
/// `controller::stop_server_if_unused` 的「在用」同一口径,隐藏的应用也算)。
fn routing_in_use(app_state: &AppState) -> 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<PanelLink>,
pub problems: Vec<PanelLink>,
pub feedback: Option<String>,
pub apps: Vec<PanelApp>,
@@ -2539,6 +2563,10 @@ pub(crate) fn collect_panel_model(app_state: &AppState) -> Result<PanelModel, Ap
}
Ok(PanelModel {
update: status.update_ready.as_ref().map(|version| PanelLink {
id: INSTALL_UPDATE_ID.to_string(),
text: fill(texts.install_update, &[("version", version)]),
}),
problems: status
.problems
.iter()
@@ -3320,6 +3348,26 @@ pub fn handle_tray_menu_event(app: &tauri::AppHandle, event_id: &str) {
match event_id {
"show_main" => 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::<String>) {
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<TrayEntry> {
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!(
+2
View File
@@ -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() {
>
<Suspense fallback={<PageLoading />}>{renderContent()}</Suspense>
</div>
<AutoUpdatePrompt />
</main>
</div>
+128
View File
@@ -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 (
<div
role="status"
aria-live="polite"
className="absolute bottom-4 end-4 z-30 w-[264px] max-w-[calc(100%-2rem)] rounded-panel border border-border bg-surface px-3 py-2.5 shadow-v7-lg duration-200 animate-in fade-in slide-in-from-bottom-2"
>
<div className="flex items-start gap-2">
<Download className="mt-0.5 h-3.5 w-3.5 shrink-0 text-action-text" />
<div className="min-w-0 flex-1 space-y-0.5">
<p className="text-body font-medium text-fg-1">
{t("autoUpdate.readyTitle", { version })}
</p>
<p className="text-caption text-fg-2">
{routingInUse
? t("autoUpdate.readyBodyRouting")
: t("autoUpdate.readyBody")}
</p>
</div>
</div>
<div className="mt-2 flex justify-end gap-1.5">
<Button
type="button"
variant="neutral"
size="compact"
onClick={handleLater}
disabled={installing}
>
{t("autoUpdate.later")}
</Button>
<Button
type="button"
variant="solid"
size="compact"
onClick={() => void handleInstall()}
disabled={installing}
>
{installing ? (
<>
<Loader2 className="h-3.5 w-3.5 animate-spin" />
{t("settings.updating")}
</>
) : (
t("autoUpdate.installNow")
)}
</Button>
</div>
</div>
);
}
+63 -4
View File
@@ -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<boolean>;
}
// 应用自身版本(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) {
</div>
)}
{onAutoSave && (
// 关于页的其它行是 px-5,这里用 SettingsRow 对齐(SettingsSwitchRow 固定 px-4)
<SettingsRow
className="px-5 py-4"
label={t("autoUpdate.toggle")}
help={{
title: t("autoUpdate.toggle"),
body: t("autoUpdate.toggleHelp"),
}}
// 灰掉的开关要写明为什么用不了
description={
autoUpdateSupported ? undefined : t("autoUpdate.unsupported")
}
control={
<Switch
checked={autoUpdateEnabled && autoUpdateSupported}
disabled={!autoUpdateSupported}
onCheckedChange={(value) => void handleAutoUpdateChange(value)}
aria-label={t("autoUpdate.toggle")}
/>
}
/>
)}
<div className="flex flex-wrap items-center gap-2 px-5 py-4">
{starPromptDismissed && (
<Button
+7 -1
View File
@@ -532,7 +532,13 @@ export function SettingsPage({
</>
);
case "about":
return <AboutSection isPortable={isPortable} />;
return (
<AboutSection
isPortable={isPortable}
autoUpdateEnabled={settings?.autoUpdateEnabled ?? false}
onAutoSave={handleAutoSave}
/>
);
}
};
+83 -4
View File
@@ -6,8 +6,10 @@ import React, {
useCallback,
useRef,
} from "react";
import type { UpdateInfo } from "../lib/updater";
import { checkForUpdate } from "../lib/updater";
import { listen } from "@tauri-apps/api/event";
import type { ReadyUpdate, UpdateInfo } from "../lib/updater";
import { UPDATE_READY_EVENT, checkForUpdate } from "../lib/updater";
import { settingsApi } from "../lib/api/settings";
import { extractErrorMessage } from "../utils/errorUtils";
interface UpdateContextValue {
@@ -24,6 +26,16 @@ interface UpdateContextValue {
// 操作方法
checkUpdate: () => Promise<boolean>;
resetDismiss: () => void;
// 自动更新(下载状态在后端,主窗口重建后从后端取回)
/** 后台已下好、等确认安装的版本 */
readyUpdate: ReadyUpdate | null;
/** 这台机器能不能自动安装(便携版、Linux 非 AppImage 不行) */
autoUpdateSupported: boolean;
/** 有应用在用路由服务(重启会切断进行中的请求),随 refreshAutoUpdate 更新 */
routingInUse: boolean;
/** 重新向后端要一次自动更新状态(开关改动后调用) */
refreshAutoUpdate: () => Promise<void>;
}
const UpdateContext = createContext<UpdateContextValue | undefined>(undefined);
@@ -57,6 +69,41 @@ export function UpdateProvider({ children }: { children: React.ReactNode }) {
setIsDismissed(dismissedVersion === current);
}, [updateInfo?.availableVersion]);
const [readyUpdate, setReadyUpdate] = useState<ReadyUpdate | null>(null);
const [autoUpdateSupported, setAutoUpdateSupported] = useState(false);
const [routingInUse, setRoutingInUse] = useState(false);
const refreshAutoUpdate = useCallback(async () => {
try {
const status = await settingsApi.getAutoUpdateStatus();
setAutoUpdateSupported(status.supported);
setReadyUpdate(status.ready);
setRoutingInUse(status.routingInUse);
} catch (err) {
console.error("读取自动更新状态失败:", err);
}
}, []);
// 后台下载在后端进行:挂载时取一次(轻量模式下主窗口会重建),之后听下载完成的事件
useEffect(() => {
void refreshAutoUpdate();
let unlisten: (() => void) | undefined;
let disposed = false;
// 载荷为 null:下好的版本被撤回,提示收起
listen<ReadyUpdate | null>(UPDATE_READY_EVENT, (event) => {
setReadyUpdate(event.payload ?? null);
})
.then((fn) => {
if (disposed) fn();
else unlisten = fn;
})
.catch((err) => console.error("监听自动更新事件失败:", err));
return () => {
disposed = true;
unlisten?.();
};
}, [refreshAutoUpdate]);
const isCheckingRef = useRef(false);
const checkUpdate = useCallback(async () => {
@@ -101,6 +148,22 @@ export function UpdateProvider({ children }: { children: React.ReactNode }) {
}
}, []);
// 后台下好了新版本,但启动时那次检查没看到(应用开着期间才发版):补查一次,
// 让更新说明跟上。每个下好的版本只补查一次:安装提示每 5 秒轮询一次状态,
// 离线时补查会一直失败,不能跟着轮询反复联网。
const readyVersion = readyUpdate?.version;
const recheckedVersionRef = useRef<string | null>(null);
useEffect(() => {
if (
readyVersion &&
updateInfo?.availableVersion !== readyVersion &&
recheckedVersionRef.current !== readyVersion
) {
recheckedVersionRef.current = readyVersion;
checkUpdate().catch(console.error);
}
}, [readyVersion, updateInfo?.availableVersion, checkUpdate]);
const dismissUpdate = useCallback(() => {
setIsDismissed(true);
if (updateInfo?.availableVersion) {
@@ -126,15 +189,31 @@ export function UpdateProvider({ children }: { children: React.ReactNode }) {
return () => clearTimeout(timer);
}, [checkUpdate]);
// 后端手里有下好的包,就算有更新:离线、或主窗口重建后联网检查还没成功,
// 侧栏红点和关于页的安装按钮也要在(安装命令离线时会直接装缓存的包)
const effectiveUpdateInfo: UpdateInfo | null =
updateInfo ??
(readyUpdate
? {
currentVersion: "",
availableVersion: readyUpdate.version,
notes: readyUpdate.notes ?? undefined,
}
: null);
const value: UpdateContextValue = {
hasUpdate,
updateInfo,
hasUpdate: hasUpdate || !!readyUpdate,
updateInfo: effectiveUpdateInfo,
isChecking,
error,
isDismissed,
dismissUpdate,
checkUpdate,
resetDismiss,
readyUpdate,
autoUpdateSupported,
routingInUse,
refreshAutoUpdate,
};
return (
+11
View File
@@ -5382,5 +5382,16 @@
"managedHint": "Dieses Konto wird in der Kontoverwaltung verwaltet; die Karte verschwindet nach der Abmeldung."
},
"deleteSessionHint": "Löschen Sie diese Sitzung in DeepSeek Harness, damit der Verlauf konsistent bleibt."
},
"autoUpdate": {
"toggle": "Updates automatisch herunterladen",
"toggleHelp": "Lädt neue Versionen im Hintergrund herunter und fragt vor der Installation nach. Ohne Ihre Bestätigung wird nichts installiert.",
"unsupported": "Nicht verfügbar für die portable Version und Linux-deb-/rpm-Pakete",
"readyTitle": "v{{version}} wurde heruntergeladen",
"readyBody": "Jetzt installieren? CC Switch wird neu gestartet.",
"readyBodyRouting": "Jetzt installieren? CC Switch wird neu gestartet, laufende Anfragen über das lokale Routing werden abgebrochen.",
"later": "Später",
"installNow": "Installieren und neu starten",
"installFailed": "Update-Installation fehlgeschlagen"
}
}
+11
View File
@@ -5382,5 +5382,16 @@
"managedHint": "This account is managed in the Auth Center; the card disappears after you sign out."
},
"deleteSessionHint": "Delete this session in DeepSeek Harness to keep its history consistent."
},
"autoUpdate": {
"toggle": "Download updates automatically",
"toggleHelp": "Downloads new versions in the background and asks before installing. Nothing is installed without your confirmation.",
"unsupported": "Not available for the portable build or Linux deb / rpm packages",
"readyTitle": "v{{version}} has been downloaded",
"readyBody": "Install it now? CC Switch will restart.",
"readyBodyRouting": "Install it now? CC Switch will restart, and requests in progress through local routing will be cut off.",
"later": "Later",
"installNow": "Install and restart",
"installFailed": "Update installation failed"
}
}
+11
View File
@@ -5382,5 +5382,16 @@
"managedHint": "アカウントは認証センターで管理します。ログアウトするとこのカードは自動で消えます。"
},
"deleteSessionHint": "履歴の整合性を保つため、DeepSeek Harness でこのセッションを削除してください。"
},
"autoUpdate": {
"toggle": "アップデートを自動でダウンロード",
"toggleHelp": "新しいバージョンをバックグラウンドでダウンロードし、インストール前に確認します。確認なしにインストールすることはありません。",
"unsupported": "ポータブル版と Linux の deb / rpm パッケージでは利用できません",
"readyTitle": "新しいバージョン v{{version}} のダウンロードが完了しました",
"readyBody": "今すぐインストールしますか?CC Switch が再起動します。",
"readyBodyRouting": "今すぐインストールしますか?CC Switch が再起動し、ローカルルーティングを経由中のリクエストは中断されます。",
"later": "後で",
"installNow": "インストールして再起動",
"installFailed": "アップデートのインストールに失敗しました"
}
}
+11
View File
@@ -5382,5 +5382,16 @@
"editDisabled": "DeepSeek Harness가 이 계정으로 사용할 수 있는 모델을 자동으로 제공하므로 편집할 필요가 없습니다.",
"managedHint": "이 계정은 인증 센터에서 관리합니다. 로그아웃하면 이 카드가 사라집니다."
}
},
"autoUpdate": {
"toggle": "업데이트 자동 다운로드",
"toggleHelp": "새 버전을 백그라운드에서 다운로드하고 설치 전에 확인합니다. 확인 없이 설치하지 않습니다.",
"unsupported": "포터블 버전과 Linux deb / rpm 패키지에서는 사용할 수 없습니다",
"readyTitle": "새 버전 v{{version}} 다운로드가 완료되었습니다",
"readyBody": "지금 설치할까요? CC Switch가 다시 시작됩니다.",
"readyBodyRouting": "지금 설치할까요? CC Switch가 다시 시작되며, 로컬 라우팅을 거쳐 진행 중인 요청이 중단됩니다.",
"later": "나중에",
"installNow": "설치 후 다시 시작",
"installFailed": "업데이트 설치에 실패했습니다"
}
}
+11
View File
@@ -5380,5 +5380,16 @@
"managedHint": "Этот аккаунт управляется в разделе «Аккаунты»; карточка исчезнет после выхода."
},
"deleteSessionHint": "Удалите эту сессию в DeepSeek Harness, чтобы её история оставалась согласованной."
},
"autoUpdate": {
"toggle": "Автоматически загружать обновления",
"toggleHelp": "Загружает новые версии в фоне и спрашивает перед установкой. Без вашего подтверждения ничего не устанавливается.",
"unsupported": "Недоступно для портативной версии и пакетов Linux deb / rpm",
"readyTitle": "Версия v{{version}} загружена",
"readyBody": "Установить сейчас? CC Switch перезапустится.",
"readyBodyRouting": "Установить сейчас? CC Switch перезапустится, текущие запросы через локальную маршрутизацию будут прерваны.",
"later": "Позже",
"installNow": "Установить и перезапустить",
"installFailed": "Не удалось установить обновление"
}
}
+11
View File
@@ -5382,5 +5382,16 @@
"expiryShowAll": "Her kredi grubunun son kullanma tarihini göster",
"inTime": "{{time}}'de"
}
},
"autoUpdate": {
"toggle": "Güncellemeleri otomatik indir",
"toggleHelp": "Yeni sürümleri arka planda indirir ve kurmadan önce sorar. Onayınız olmadan hiçbir şey kurulmaz.",
"unsupported": "Taşınabilir sürümde ve Linux deb / rpm paketlerinde kullanılamaz",
"readyTitle": "v{{version}} sürümü indirildi",
"readyBody": "Şimdi kurulsun mu? CC Switch yeniden başlatılacak.",
"readyBodyRouting": "Şimdi kurulsun mu? CC Switch yeniden başlatılacak ve yerel yönlendirme üzerinden devam eden istekler kesilecek.",
"later": "Daha sonra",
"installNow": "Kur ve yeniden başlat",
"installFailed": "Güncelleme kurulamadı"
}
}
+11
View File
@@ -5382,5 +5382,16 @@
"managedHint": "帳號在授權中心管理:登出後這張卡會自動消失。"
},
"deleteSessionHint": "請在 DeepSeek Harness 中刪除此工作階段,以保持原生歷史記錄一致。"
},
"autoUpdate": {
"toggle": "自動下載更新",
"toggleHelp": "在背景下載新版本,下載完成後詢問是否安裝,不會未經確認就安裝。",
"unsupported": "可攜版和 Linux 的 deb / rpm 安裝套件不支援自動更新",
"readyTitle": "新版本 v{{version}} 已下載完成",
"readyBody": "現在安裝嗎?CC Switch 會重新啟動。",
"readyBodyRouting": "現在安裝嗎?CC Switch 會重新啟動,正在經本地路由的請求會中斷。",
"later": "稍後",
"installNow": "安裝並重新啟動",
"installFailed": "安裝更新失敗"
}
}
+11
View File
@@ -5382,5 +5382,16 @@
"managedHint": "账号在授权中心管理:退出登录后这张卡会自动消失。"
},
"deleteSessionHint": "请在 DeepSeek Harness 中删除此会话,以保持原生历史记录一致。"
},
"autoUpdate": {
"toggle": "自动下载更新",
"toggleHelp": "在后台下载新版本,下载完成后询问是否安装,不会未经确认就安装。",
"unsupported": "便携版和 Linux 的 deb / rpm 安装包不支持自动更新",
"readyTitle": "新版本 v{{version}} 已下载完成",
"readyBody": "现在安装吗?CC Switch 会重启。",
"readyBodyRouting": "现在安装吗?CC Switch 会重启,正在经本地路由的请求会中断。",
"later": "稍后",
"installNow": "安装并重启",
"installFailed": "安装更新失败"
}
}
+10
View File
@@ -6,6 +6,7 @@ import type {
RemoteSnapshotInfo,
} from "@/types";
import type { AppId } from "./types";
import type { AutoUpdateStatus, ReadyUpdate } from "@/lib/updater";
export interface ConfigTransferResult {
success: boolean;
@@ -77,6 +78,15 @@ export const settingsApi = {
return await invoke("install_update_and_restart");
},
async getAutoUpdateStatus(): Promise<AutoUpdateStatus> {
return await invoke("get_auto_update_status");
},
/** 立刻在后台检查并下载最新版本(打开自动更新开关时调用) */
async downloadAppUpdate(): Promise<ReadyUpdate | null> {
return await invoke("download_app_update");
},
async checkUpdates(): Promise<void> {
await invoke("check_for_updates");
},
+19
View File
@@ -9,6 +9,25 @@ export interface UpdateInfo {
pubDate?: string;
}
/** 自动更新在后台下好、等用户确认安装的版本(后端 `app_update::ReadyUpdate`)。 */
export interface ReadyUpdate {
version: string;
notes?: string | null;
}
/** 后端 `app_update::AutoUpdateStatus`。 */
export interface AutoUpdateStatus {
/** 这台机器能不能自动安装(便携版、Linux 非 AppImage 不行) */
supported: boolean;
downloading: boolean;
ready: ReadyUpdate | null;
/** 有应用在用路由服务:重启会切断进行中的请求 */
routingInUse: boolean;
}
/** 待安装版本变了的事件,载荷是 {@link ReadyUpdate};null 表示下好的版本被撤回 */
export const UPDATE_READY_EVENT = "app-update-ready";
export interface CheckOptions {
timeout?: number;
channel?: UpdateChannel;
+17
View File
@@ -15,6 +15,7 @@ import {
Check,
ChevronLeft,
ChevronRight,
Download,
ExternalLink,
Feather,
Loader2,
@@ -1078,6 +1079,22 @@ export function TrayPanel() {
<Loader2 className="h-4 w-4 animate-spin text-muted-foreground" />
</div>
)}
{state?.update && (
<button
key={state.update.id}
type="button"
data-other-item
onClick={() => action(state.update!.id)}
className={cn(
"flex items-start gap-2 rounded-lg px-2.5 py-1.5 text-left text-xs font-medium text-blue-500",
FOCUS_RING,
ROW_HOVER,
)}
>
<Download className="mt-0.5 h-3.5 w-3.5 shrink-0" />
<span>{state.update.text}</span>
</button>
)}
{state?.problems.map((problem) => (
<button
key={problem.id}
+2
View File
@@ -82,6 +82,8 @@ export interface PanelApp {
/** 托盘面板的数据(后端 `tray::PanelModel`)。 */
export interface TrayPanelState {
/** 自动更新已下好新版本:点了重启安装 */
update?: PanelLink | null;
problems: PanelLink[];
feedback: string | null;
apps: PanelApp[];
+2
View File
@@ -435,6 +435,8 @@ export interface Settings {
showProviderSearch?: boolean;
// 启动时检查已安装的命令行应用有没有新版本(默认关)
checkToolUpdatesOnStartup?: boolean;
// 自动下载 CC Switch 新版本,下好后问要不要安装(默认关;设备级,不随云同步)
autoUpdateEnabled?: boolean;
// 点托盘图标出原生菜单,不出托盘面板(macOS / Windows;Linux 一律原生菜单;默认关,没写过视为关,即用托盘面板)
nativeTrayMenu?: boolean;
// Preserve Codex ChatGPT login in auth.json when switching third-party providers
@@ -0,0 +1,83 @@
import { render, screen, waitFor } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { AutoUpdatePrompt } from "@/components/AutoUpdatePrompt";
const update = vi.hoisted(() => ({
readyUpdate: null as { version: string } | null,
routingInUse: false,
refreshAutoUpdate: vi.fn(async () => {}),
resetDismiss: vi.fn(),
}));
const api = vi.hoisted(() => ({
installUpdateAndRestart: vi.fn(async () => true),
}));
vi.mock("react-i18next", () => ({
useTranslation: () => ({
t: (key: string, options?: { version?: string }) =>
options?.version ? `${key}:${options.version}` : key,
}),
}));
vi.mock("@/contexts/UpdateContext", () => ({
useUpdate: () => update,
}));
vi.mock("@/lib/api", () => ({
settingsApi: api,
}));
const DISMISSED_KEY = "ccswitch:autoUpdate:promptDismissedVersion";
describe("AutoUpdatePrompt", () => {
beforeEach(() => {
localStorage.clear();
update.readyUpdate = null;
update.routingInUse = false;
api.installUpdateAndRestart.mockClear();
update.refreshAutoUpdate.mockClear();
});
it("renders nothing until an update has been downloaded", () => {
const { container } = render(<AutoUpdatePrompt />);
expect(container).toBeEmptyDOMElement();
});
it("asks before installing and warns when routing is in use", () => {
update.readyUpdate = { version: "4.1.0" };
update.routingInUse = true;
render(<AutoUpdatePrompt />);
expect(screen.getByText("autoUpdate.readyTitle:4.1.0")).toBeInTheDocument();
expect(screen.getByText("autoUpdate.readyBodyRouting")).toBeInTheDocument();
expect(api.installUpdateAndRestart).not.toHaveBeenCalled();
});
it("installs only when the user confirms", async () => {
update.readyUpdate = { version: "4.1.0" };
render(<AutoUpdatePrompt />);
await userEvent.click(screen.getByText("autoUpdate.installNow"));
expect(api.installUpdateAndRestart).toHaveBeenCalledTimes(1);
});
it("'Later' hides the prompt for that version and remembers it", async () => {
update.readyUpdate = { version: "4.1.0" };
const { container, rerender } = render(<AutoUpdatePrompt />);
await userEvent.click(screen.getByText("autoUpdate.later"));
expect(container).toBeEmptyDOMElement();
expect(localStorage.getItem(DISMISSED_KEY)).toBe("4.1.0");
// 之后下好了更新的版本,照样再问
update.readyUpdate = { version: "4.1.1" };
rerender(<AutoUpdatePrompt />);
await waitFor(() =>
expect(
screen.getByText("autoUpdate.readyTitle:4.1.1"),
).toBeInTheDocument(),
);
});
});
@@ -0,0 +1,89 @@
import { act, render, screen, waitFor } from "@testing-library/react";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { UpdateProvider, useUpdate } from "@/contexts/UpdateContext";
const mocks = vi.hoisted(() => ({
status: {
supported: true,
downloading: false,
ready: null as { version: string } | null,
routingInUse: false,
},
checkForUpdate: vi.fn(),
}));
vi.mock("@tauri-apps/api/event", () => ({
listen: vi.fn(async () => () => {}),
}));
vi.mock("@/lib/api/settings", () => ({
settingsApi: {
// 每次返回新对象,和真实 IPC 一样
getAutoUpdateStatus: vi.fn(async () => ({
...mocks.status,
ready: mocks.status.ready ? { ...mocks.status.ready } : null,
})),
},
}));
vi.mock("@/lib/updater", async (importOriginal) => ({
...(await importOriginal<typeof import("@/lib/updater")>()),
checkForUpdate: mocks.checkForUpdate,
}));
let ctx: ReturnType<typeof useUpdate>;
function Probe() {
ctx = useUpdate();
return (
<div data-testid="probe">
{String(ctx.hasUpdate)}:{ctx.updateInfo?.availableVersion ?? "-"}
</div>
);
}
describe("UpdateProvider auto update", () => {
beforeEach(() => {
vi.useRealTimers();
mocks.status.ready = null;
mocks.checkForUpdate.mockReset();
});
it("treats a downloaded package as an available update even when the online check fails", async () => {
mocks.status.ready = { version: "4.1.0" };
mocks.checkForUpdate.mockRejectedValue(new Error("offline"));
render(
<UpdateProvider>
<Probe />
</UpdateProvider>,
);
await waitFor(() =>
expect(screen.getByTestId("probe")).toHaveTextContent("true:4.1.0"),
);
});
it("rechecks online at most once per downloaded version while the prompt polls", async () => {
mocks.status.ready = { version: "4.1.0" };
mocks.checkForUpdate.mockRejectedValue(new Error("offline"));
render(
<UpdateProvider>
<Probe />
</UpdateProvider>,
);
await waitFor(() => expect(ctx.readyUpdate?.version).toBe("4.1.0"));
// 启动检查(1 秒后)之外,补查只该发生一次
await waitFor(() => expect(mocks.checkForUpdate).toHaveBeenCalled());
const callsAfterFirstRecheck = mocks.checkForUpdate.mock.calls.length;
for (let i = 0; i < 3; i += 1) {
await act(async () => {
await ctx.refreshAutoUpdate();
});
}
expect(mocks.checkForUpdate.mock.calls.length).toBe(
callsAfterFirstRecheck,
);
});
});