From ef179fcf61e85e5c9141113132e6c603c4137f5d Mon Sep 17 00:00:00 2001 From: Evan Date: Fri, 31 Jul 2026 06:52:10 +0800 Subject: [PATCH] fix(home): manual update check not working when auto_check_update disabled (#7585) * fix(config): prevent cleanup_orphaned_files from deleting active profiles When IProfiles::new() fails to parse profiles.yaml (e.g., corrupt file), it returns Self::default() with items: None. The subsequent cleanup_orphaned_files() call then sees no active files and deletes all profile files in the profiles/ directory except the two hardcoded protected files (Merge.yaml and Script.js). Guard cleanup_orphaned_files() against this by checking if items is None or empty before proceeding. When items is unavailable, skip the cleanup and log a warning instead of blindly deleting user data. Fixes #7577 * fix(home): manual update check not working when auto_check_update disabled When auto_check_update is false, useUpdate() sets enabled=false for the SWR query, which sets the SWR key to null. Calling swr.mutate() on a null key does not execute the queryFn, returning undefined instead. This caused the home page's "last check time" click to instantly show "already up to date" without actually checking for updates. Fix: use revalidateQuery() for the manual checkUpdate function, which uses the global SWR mutate with the actual query key, bypassing the enabled: false state and always triggering a real network request. Fixes #7584 * fix: preserve manual update and profile data --------- Co-authored-by: Evan Gong Co-authored-by: wonfen <96291150+wonfen@users.noreply.github.com> Co-authored-by: wonfen --- src-tauri/src/config/config.rs | 44 +++++++++++++++++++++++++++++--- src-tauri/src/config/profiles.rs | 25 ++++++++++++++++-- src/hooks/use-update.test.tsx | 32 +++++++++++++++++++++++ src/hooks/use-update.ts | 25 ++++++++++-------- 4 files changed, 110 insertions(+), 16 deletions(-) create mode 100644 src/hooks/use-update.test.tsx diff --git a/src-tauri/src/config/config.rs b/src-tauri/src/config/config.rs index 460869d07..fe402bcd7 100644 --- a/src-tauri/src/config/config.rs +++ b/src-tauri/src/config/config.rs @@ -1,6 +1,6 @@ use super::{IClashTemp, IProfiles, IVerge}; use crate::{ - config::{PrfItem, profiles_append_item_safe, runtime::IRuntime}, + config::{PrfItem, profiles_append_item_to_safe, runtime::IRuntime}, constants::{files, timing}, core::{ CoreManager, @@ -143,13 +143,26 @@ impl Config { // Ensure "Merge" and "Script" profile items exist, adding them if missing. async fn ensure_default_profile_items() -> Result<()> { let profiles = Self::profiles().await; + Self::ensure_default_profile_items_for(&profiles).await + } + + async fn ensure_default_profile_items_for(profiles: &Draft) -> Result<()> { + if profiles.latest_arc().get_items().is_none() { + logging!( + warn, + Type::Config, + "Profile items 无法加载,跳过默认项初始化以保留现有配置文件" + ); + return Ok(()); + } + if profiles.latest_arc().get_item("Merge").is_err() { let merge_item = &mut PrfItem::from_merge(Some("Merge".into()))?; - profiles_append_item_safe(merge_item).await?; + profiles_append_item_to_safe(profiles, merge_item).await?; } if profiles.latest_arc().get_item("Script").is_err() { let script_item = &mut PrfItem::from_script(Some("Script".into()))?; - profiles_append_item_safe(script_item).await?; + profiles_append_item_to_safe(profiles, script_item).await?; } Ok(()) } @@ -403,4 +416,29 @@ mod tests { let box_iruntime_size = std::mem::size_of_val(&draft); assert_eq!(box_iruntime_size, std::mem::size_of::>>()); } + + #[tokio::test] + async fn failed_profile_index_survives_startup_without_cleanup() -> Result<()> { + let profiles = Draft::new(IProfiles::default()); + let profiles_dir = std::env::temp_dir().join(format!("clash-verge-profile-cleanup-{}", nanoid::nanoid!())); + tokio::fs::create_dir_all(&profiles_dir).await?; + let active_profile = profiles_dir.join("Ractive.yaml"); + tokio::fs::write(&active_profile, "proxies: []").await?; + + Config::ensure_default_profile_items_for(&profiles).await?; + profiles.data_arc().cleanup_orphaned_files_in(&profiles_dir).await?; + + let profile_was_preserved = tokio::fs::try_exists(&active_profile).await?; + tokio::fs::remove_dir_all(&profiles_dir).await?; + + assert!( + profile_was_preserved, + "startup must not delete profiles when profiles.yaml could not be loaded" + ); + assert!( + profiles.data_arc().get_items().is_none(), + "startup must not replace an unreadable profile index with defaults" + ); + Ok(()) + } } diff --git a/src-tauri/src/config/profiles.rs b/src-tauri/src/config/profiles.rs index e8eea22f9..fba888dce 100644 --- a/src-tauri/src/config/profiles.rs +++ b/src-tauri/src/config/profiles.rs @@ -10,6 +10,7 @@ use crate::{ }, }; use anyhow::{Context as _, Result, bail}; +use clash_verge_draft::Draft; use clash_verge_logging::{Type, logging}; use parking_lot::Mutex; use serde::{Deserialize, Serialize}; @@ -434,11 +435,27 @@ impl IProfiles { /// 以 app 中的 profile 列表为准,删除不再需要的文件 pub async fn cleanup_orphaned_files(&self) -> Result<()> { let profiles_dir = dirs::app_profiles_dir()?; + self.cleanup_orphaned_files_in(&profiles_dir).await + } + pub(super) async fn cleanup_orphaned_files_in(&self, profiles_dir: &Path) -> Result<()> { if !profiles_dir.exists() { return Ok(()); } + // 如果 items 为空(例如 profiles.yaml 解析失败导致 + // IProfiles::new() 返回 default),此时无法判断哪些文件是活跃的, + // 跳过清理以避免误删用户正在使用的订阅配置文件。 + // See: https://github.com/clash-verge-rev/clash-verge-rev/issues/7577 + if self.items.as_ref().is_none_or(|v| v.is_empty()) { + logging!( + warn, + Type::Config, + "Profile items 为空,跳过孤儿文件清理以避免误删活跃的配置文件" + ); + return Ok(()); + } + // 获取所有 active profile 的文件名集合 let active_files = self.get_all_active_files(); @@ -586,8 +603,12 @@ pub async fn profiles_append_item_with_filedata_safe(item: &PrfItem, file_data: } pub async fn profiles_append_item_safe(item: &mut PrfItem) -> Result<()> { - Config::profiles() - .await + let profiles = Config::profiles().await; + profiles_append_item_to_safe(&profiles, item).await +} + +pub(super) async fn profiles_append_item_to_safe(profiles: &Draft, item: &mut PrfItem) -> Result<()> { + profiles .with_data_modify(|mut profiles| async move { profiles.append_item(item).await?; Ok((profiles, ())) diff --git a/src/hooks/use-update.test.tsx b/src/hooks/use-update.test.tsx new file mode 100644 index 000000000..5a24877f8 --- /dev/null +++ b/src/hooks/use-update.test.tsx @@ -0,0 +1,32 @@ +// @vitest-environment jsdom +import { act, renderHook, waitFor } from '@testing-library/react' +import { beforeEach, expect, test, vi } from 'vitest' + +import { setPreloadConfig } from '@/services/preload' + +import { useUpdate } from './use-update' + +const check = vi.hoisted(() => vi.fn()) + +vi.mock('@tauri-apps/plugin-updater', () => ({ check })) + +beforeEach(() => { + localStorage.clear() + setPreloadConfig({ auto_check_update: false } as IVergeConfig) + check.mockReset() +}) + +test('manual update check works when automatic checks are disabled', async () => { + const availableUpdate = { version: '9.9.9' } + check.mockResolvedValueOnce(availableUpdate) + const { result } = renderHook(() => useUpdate()) + + let checked + await act(async () => { + checked = await result.current.checkUpdate() + }) + + expect(check).toHaveBeenCalledOnce() + expect(checked).toEqual({ data: availableUpdate }) + await waitFor(() => expect(result.current.lastCheckUpdate).not.toBeNull()) +}) diff --git a/src/hooks/use-update.ts b/src/hooks/use-update.ts index ca12cb426..fb7df6125 100644 --- a/src/hooks/use-update.ts +++ b/src/hooks/use-update.ts @@ -1,4 +1,4 @@ -import { setCacheData, useQuery } from '@/services/query-client' +import { fetchCacheData, setCacheData, useQuery } from '@/services/query-client' import { checkUpdateSafe } from '@/services/update' import { useVerge } from './use-verge' @@ -30,17 +30,15 @@ export const useUpdate = (enabled: boolean = true) => { // Otherwise, respect the auto_check_update setting (or default to true if null/undefined for manual triggers) const shouldCheck = enabled && auto_check_update !== false - const { - data: updateInfo, - refetch: checkUpdate, - isFetching: isValidating, - } = useQuery({ + const fetchUpdate = async () => { + const result = await checkUpdateSafe() + updateLastCheckTime() + return result + } + + const { data: updateInfo, isFetching: isValidating } = useQuery({ queryKey: ['checkUpdate'], - queryFn: async () => { - const result = await checkUpdateSafe() - updateLastCheckTime() - return result - }, + queryFn: fetchUpdate, enabled: shouldCheck, retry: 2, staleTime: 60 * 60 * 1000, @@ -49,6 +47,11 @@ export const useUpdate = (enabled: boolean = true) => { refetchOnWindowFocus: false, }) + const checkUpdate = async () => { + const data = await fetchCacheData(['checkUpdate'], fetchUpdate) + return { data } + } + // Shared last check timestamp const { data: lastCheckUpdate } = useQuery({ queryKey: [LAST_CHECK_KEY],