diff --git a/src-tauri/src/cmd/profile.rs b/src-tauri/src/cmd/profile.rs index 6ed54f332..7d66caebc 100644 --- a/src-tauri/src/cmd/profile.rs +++ b/src-tauri/src/cmd/profile.rs @@ -213,16 +213,8 @@ async fn restore_previous_profile(prev_profile: &String) -> CmdResult<()> { async fn handle_success(current_value: Option<&String>) -> CmdResult { Config::profiles().await.apply(); + // Runtime refresh and tray rebuilding happen after saved node selections are restored. profiles::activate_selected_nodes().stringify_err()?; - handle::Handle::refresh_clash(); - - if let Err(e) = Tray::global().update_tooltip().await { - logging!(warn, Type::Cmd, "Warning: 异步更新托盘提示失败: {e}"); - } - - if let Err(e) = Tray::global().update_menu().await { - logging!(warn, Type::Cmd, "Warning: 异步更新托盘菜单失败: {e}"); - } if let Err(e) = profiles_save_file_safe().await { logging!(warn, Type::Cmd, "Warning: 异步保存配置文件失败: {e}"); diff --git a/src-tauri/src/config/profiles.rs b/src-tauri/src/config/profiles.rs index 16374008a..c6e063893 100644 --- a/src-tauri/src/config/profiles.rs +++ b/src-tauri/src/config/profiles.rs @@ -3,7 +3,7 @@ use super::{ prfitem::{PrfItem, PrfSelected}, }; use crate::{ - core::handle, + core::{handle, tray::Tray}, utils::{ dirs::{self, PathBufExec as _}, help, @@ -16,7 +16,7 @@ use serde::{Deserialize, Serialize}; use serde_yaml_ng::Mapping; use smartstring::alias::String; use std::{ - collections::HashSet, + collections::{HashMap, HashSet}, sync::{ LazyLock, atomic::{AtomicU64, Ordering}, @@ -762,6 +762,73 @@ async fn select_node_with_timeout(group_name: &String, node: &String) -> Result< .with_context(|| format!("failed to select node [{node}] for group [{group_name}]")) } +fn remaining_activations( + activations: &[(String, String)], + completed: &HashMap, +) -> Vec<(String, String)> { + activations + .iter() + .filter(|(group_name, node)| completed.get(group_name) != Some(node)) + .cloned() + .collect() +} + +async fn apply_activations( + activations: &[(String, String)], + completed: &mut HashMap, + generation: u64, +) -> Option { + let mut activated_count = 0; + for (group_name, node) in remaining_activations(activations, completed) { + if !is_activation_current(generation) { + return None; + } + match select_node_with_timeout(&group_name, &node).await { + Ok(()) => { + if !is_activation_current(generation) { + return None; + } + logging!( + info, + Type::Config, + "Selected node for proxy: {group_name}, node: {node}" + ); + completed.insert(group_name, node); + activated_count += 1; + } + Err(err) => logging!(error, Type::Config, "{err:#}"), + } + if !is_activation_current(generation) { + return None; + } + } + Some(activated_count) +} + +async fn update_tray_after_activation(generation: u64) { + if !is_activation_current(generation) { + return; + } + if let Err(err) = Tray::global().update_tooltip().await { + logging!( + warn, + Type::Config, + "failed to update tray tooltip after profile switch: {err:#}" + ); + } + + if !is_activation_current(generation) { + return; + } + if let Err(err) = Tray::global().update_menu().await { + logging!( + warn, + Type::Config, + "failed to update tray menu after profile switch: {err:#}" + ); + } +} + async fn persist_reconciled_selected( profile_uid: &String, original_selected: &[PrfSelected], @@ -812,35 +879,55 @@ async fn activate_selected_nodes_worker( return Ok(()); } - let (previous_snapshot, current_snapshot) = if selected_nodes_need_confirmation(&selected, &first_snapshot) { + let needs_confirmation = selected_nodes_need_confirmation(&selected, &first_snapshot); + let immediate_plan = reconcile_selected_nodes(&selected, None, &first_snapshot); + logging!( + debug, + Type::Config, + "immediate selected nodes activation plan: {immediate_plan:?}" + ); + + let mut completed_activations = HashMap::new(); + if apply_activations(&immediate_plan.activations, &mut completed_activations, generation) + .await + .is_none() + { + return Ok(()); + } + + if is_activation_current(generation) { + handle::Handle::refresh_clash(); + } + + let plan = if needs_confirmation { tokio::time::sleep(SELECTED_NODES_RECHECK_DELAY).await; if !is_activation_current(generation) { return Ok(()); } - let current_snapshot = fetch_proxies_with_timeout().await?; - (Some(first_snapshot), current_snapshot) - } else { - (None, first_snapshot) - }; - if !is_activation_current(generation) { - return Ok(()); - } - - let plan = reconcile_selected_nodes(&selected, previous_snapshot.as_ref(), ¤t_snapshot); - logging!(debug, Type::Config, "selected nodes activation plan: {plan:?}"); - - for (group_name, node) in &plan.activations { + let second_snapshot = fetch_proxies_with_timeout().await?; if !is_activation_current(generation) { return Ok(()); } - match select_node_with_timeout(group_name, node).await { - Ok(()) => logging!( - info, - Type::Config, - "Selected node for proxy: {group_name}, node: {node}" - ), - Err(err) => logging!(error, Type::Config, "{err:#}"), + let confirmed_plan = reconcile_selected_nodes(&selected, Some(&first_snapshot), &second_snapshot); + logging!( + debug, + Type::Config, + "confirmed selected nodes activation plan: {confirmed_plan:?}" + ); + let Some(confirmed_activated_count) = + apply_activations(&confirmed_plan.activations, &mut completed_activations, generation).await + else { + return Ok(()); + }; + if confirmed_activated_count > 0 && is_activation_current(generation) { + handle::Handle::refresh_clash(); } + confirmed_plan + } else { + immediate_plan + }; + if !is_activation_current(generation) { + return Ok(()); } if plan.repaired_count > 0 && is_activation_current(generation) { @@ -853,9 +940,6 @@ async fn activate_selected_nodes_worker( persist_reconciled_selected(&profile_uid, &selected, plan.selected, generation).await?; } - if is_activation_current(generation) { - handle::Handle::refresh_clash(); - } Ok(()) } @@ -884,6 +968,9 @@ pub fn activate_selected_nodes() -> Result<()> { .unwrap_or_default(); if selected.is_empty() { + if is_activation_current(generation) { + handle::Handle::refresh_clash(); + } return Ok(()); } activate_selected_nodes_worker(current, selected, generation).await @@ -893,7 +980,10 @@ pub fn activate_selected_nodes() -> Result<()> { if is_activation_current(generation) { if let Err(err) = result { logging!(error, Type::Config, "failed to activate selected nodes: {err:#}"); + // The profile itself is already active even if node restoration failed. + handle::Handle::refresh_clash(); } + update_tray_after_activation(generation).await; logging!(info, Type::Config, "activating selected nodes done!"); } }); @@ -905,7 +995,6 @@ pub fn activate_selected_nodes() -> Result<()> { #[cfg(test)] mod tests { use super::*; - use std::collections::HashMap; use tauri_plugin_mihomo::models::Proxy; fn selected(group: &str, node: &str) -> PrfSelected { @@ -1051,4 +1140,38 @@ mod tests { assert_eq!(plan.activations, vec![("group".into(), "new".into())]); assert_eq!(plan.repaired_count, 1); } + + #[test] + fn activates_valid_nodes_before_confirming_invalid_records() { + let saved = vec![selected("valid-group", "saved"), selected("stale-group", "missing")]; + let first_snapshot = proxies(vec![ + ("valid-group", &["current", "saved"], Some("current")), + ("stale-group", &["fallback"], Some("fallback")), + ]); + + assert!(selected_nodes_need_confirmation(&saved, &first_snapshot)); + let immediate_plan = reconcile_selected_nodes(&saved, None, &first_snapshot); + + assert_eq!(immediate_plan.selected, saved); + assert_eq!(immediate_plan.activations, vec![("valid-group".into(), "saved".into())]); + assert_eq!(immediate_plan.repaired_count, 0); + } + + #[test] + fn skips_only_activations_that_already_succeeded() { + let activations = vec![ + ("first-group".into(), "saved".into()), + ("second-group".into(), "new".into()), + ("first-group".into(), "replacement".into()), + ]; + let completed = HashMap::from([("first-group".into(), "saved".into())]); + + assert_eq!( + remaining_activations(&activations, &completed), + vec![ + ("second-group".into(), "new".into()), + ("first-group".into(), "replacement".into()), + ] + ); + } } diff --git a/src/hooks/use-profiles.ts b/src/hooks/use-profiles.ts index 15be12b13..ca11f374e 100644 --- a/src/hooks/use-profiles.ts +++ b/src/hooks/use-profiles.ts @@ -1,5 +1,7 @@ +import { useCallback, useRef } from 'react' + import { getProfiles, patchProfile, patchProfilesConfig } from '@/services/cmds' -import { useQuery } from '@/services/query-client' +import { setCacheDataAsync, useQuery } from '@/services/query-client' import { debugLog } from '@/utils/debug' export const useProfiles = () => { @@ -26,46 +28,44 @@ export const useProfiles = () => { refetchInterval: false, }) - const mutateProfiles = async () => { - await refetch() - } + const refetchRef = useRef(refetch) + refetchRef.current = refetch + const mutateProfiles = useCallback(async () => { + await refetchRef.current() + }, []) - const patchProfiles = async ( - value: Partial, - signal?: AbortSignal, - options?: { deferRefreshOnSuccess?: boolean }, - ) => { - try { - if (signal?.aborted) { - throw new DOMException('Operation was aborted', 'AbortError') - } - const success = await patchProfilesConfig(value) + const patchProfiles = useCallback( + async (value: Partial) => { + try { + const outcome = await patchProfilesConfig(value) - if (signal?.aborted) { - throw new DOMException('Operation was aborted', 'AbortError') - } + if (outcome.status === 'valid') { + await setCacheDataAsync( + ['getProfiles'], + (current) => (current ? { ...current, ...value } : current), + ) + } else if (outcome.status !== 'busy') { + await mutateProfiles() + } - if (!options?.deferRefreshOnSuccess || !success) { + return outcome + } catch (error) { await mutateProfiles() - } - - return success - } catch (error) { - if (error instanceof DOMException && error.name === 'AbortError') { throw error } + }, + [mutateProfiles], + ) - await mutateProfiles() - throw error - } - } - - const patchCurrent = async (value: Partial) => { - if (profiles?.current) { - await patchProfile(profiles.current, value) - mutateProfiles() - } - } + const patchCurrent = useCallback( + async (value: Partial) => { + if (profiles?.current) { + await patchProfile(profiles.current, value) + void mutateProfiles() + } + }, + [mutateProfiles, profiles], + ) return { profiles, diff --git a/src/locales/ar/profiles.json b/src/locales/ar/profiles.json index 5d81ef166..8e8cbd0a5 100644 --- a/src/locales/ar/profiles.json +++ b/src/locales/ar/profiles.json @@ -37,7 +37,7 @@ "importSuccess": "Profile imported successfully, please restart if not visible", "profileSwitched": "تم التبديل إلى الملف الشخصي", "profileReactivated": "تم إعادة تنشيط الملف الشخصي", - "switchInterrupted": "Profile switch interrupted by new selection", + "switchBusy": "Profile switch is already in progress", "batchDeleted": "Selected profiles deleted successfully" }, "notices": { diff --git a/src/locales/de/profiles.json b/src/locales/de/profiles.json index 4beeec90d..1a18f04c1 100644 --- a/src/locales/de/profiles.json +++ b/src/locales/de/profiles.json @@ -37,7 +37,7 @@ "importSuccess": "Profile imported successfully, please restart if not visible", "profileSwitched": "Abonnement gewechselt", "profileReactivated": "Abonnement erneut aktiviert", - "switchInterrupted": "Profile switch interrupted by new selection", + "switchBusy": "Profile switch is already in progress", "batchDeleted": "Selected profiles deleted successfully" }, "notices": { diff --git a/src/locales/en/profiles.json b/src/locales/en/profiles.json index c4461dead..130519774 100644 --- a/src/locales/en/profiles.json +++ b/src/locales/en/profiles.json @@ -37,7 +37,7 @@ "importSuccess": "Profile imported successfully, please restart if not visible", "profileSwitched": "Profile Switched", "profileReactivated": "Profile Reactivated", - "switchInterrupted": "Profile switch interrupted by new selection", + "switchBusy": "Profile switch is already in progress", "batchDeleted": "Selected profiles deleted successfully" }, "notices": { diff --git a/src/locales/es/profiles.json b/src/locales/es/profiles.json index e70887a6f..3044e89c7 100644 --- a/src/locales/es/profiles.json +++ b/src/locales/es/profiles.json @@ -37,7 +37,7 @@ "importSuccess": "Profile imported successfully, please restart if not visible", "profileSwitched": "Suscripción cambiada", "profileReactivated": "Suscripción reactivada", - "switchInterrupted": "Profile switch interrupted by new selection", + "switchBusy": "Profile switch is already in progress", "batchDeleted": "Selected profiles deleted successfully" }, "notices": { diff --git a/src/locales/fa/profiles.json b/src/locales/fa/profiles.json index 68b80465c..18743f819 100644 --- a/src/locales/fa/profiles.json +++ b/src/locales/fa/profiles.json @@ -37,7 +37,7 @@ "importSuccess": "Profile imported successfully, please restart if not visible", "profileSwitched": "پروفایل تغییر یافت", "profileReactivated": "پروفایل مجدداً فعال شد", - "switchInterrupted": "Profile switch interrupted by new selection", + "switchBusy": "Profile switch is already in progress", "batchDeleted": "Selected profiles deleted successfully" }, "notices": { diff --git a/src/locales/id/profiles.json b/src/locales/id/profiles.json index 801350cba..ffb4d3ae2 100644 --- a/src/locales/id/profiles.json +++ b/src/locales/id/profiles.json @@ -37,7 +37,7 @@ "importSuccess": "Profile imported successfully, please restart if not visible", "profileSwitched": "Profil Beralih", "profileReactivated": "Profil Diaktifkan Kembali", - "switchInterrupted": "Profile switch interrupted by new selection", + "switchBusy": "Profile switch is already in progress", "batchDeleted": "Selected profiles deleted successfully" }, "notices": { diff --git a/src/locales/jp/profiles.json b/src/locales/jp/profiles.json index 70ef312fe..8304e2519 100644 --- a/src/locales/jp/profiles.json +++ b/src/locales/jp/profiles.json @@ -37,7 +37,7 @@ "importSuccess": "Profile imported successfully, please restart if not visible", "profileSwitched": "プロファイルが切り替えられました。", "profileReactivated": "プロファイルが再アクティブ化されました。", - "switchInterrupted": "Profile switch interrupted by new selection", + "switchBusy": "Profile switch is already in progress", "batchDeleted": "選択したプロファイルが正常に削除されました" }, "notices": { diff --git a/src/locales/ko/profiles.json b/src/locales/ko/profiles.json index 9ab2eaed4..ded11350b 100644 --- a/src/locales/ko/profiles.json +++ b/src/locales/ko/profiles.json @@ -37,7 +37,7 @@ "importSuccess": "프로필을 성공적으로 가져왔습니다. 보이지 않으면 재시작하세요", "profileSwitched": "프로필 전환됨", "profileReactivated": "프로필 재활성화됨", - "switchInterrupted": "새 선택으로 인해 프로필 전환이 중단되었습니다", + "switchBusy": "프로필 전환이 이미 진행 중입니다", "batchDeleted": "선택한 프로필이 삭제되었습니다" }, "notices": { diff --git a/src/locales/ru/profiles.json b/src/locales/ru/profiles.json index 8a72682c7..71dde696d 100644 --- a/src/locales/ru/profiles.json +++ b/src/locales/ru/profiles.json @@ -37,7 +37,7 @@ "importSuccess": "Профиль успешно импортирован. Перезапустите приложение, если он не появился", "profileSwitched": "Профиль переключён", "profileReactivated": "Профиль перезапущен", - "switchInterrupted": "Переключение профиля прервано новым выбором", + "switchBusy": "Переключение профиля уже выполняется", "batchDeleted": "Выбранные профили удалены" }, "notices": { diff --git a/src/locales/tr/profiles.json b/src/locales/tr/profiles.json index 8d636593c..3ad749750 100644 --- a/src/locales/tr/profiles.json +++ b/src/locales/tr/profiles.json @@ -37,7 +37,7 @@ "importSuccess": "Profile imported successfully, please restart if not visible", "profileSwitched": "Profil Değiştirildi", "profileReactivated": "Profil Yeniden Etkinleştirildi", - "switchInterrupted": "Profile switch interrupted by new selection", + "switchBusy": "Profil değiştirme işlemi zaten devam ediyor", "batchDeleted": "Seçili profiller başarıyla silindi" }, "notices": { diff --git a/src/locales/tt/profiles.json b/src/locales/tt/profiles.json index 84d2dbe0a..aa92f1aa4 100644 --- a/src/locales/tt/profiles.json +++ b/src/locales/tt/profiles.json @@ -37,7 +37,7 @@ "importSuccess": "Profile imported successfully, please restart if not visible", "profileSwitched": "Профиль алмаштырылды", "profileReactivated": "Профиль яңадан активлаштырылды", - "switchInterrupted": "Profile switch interrupted by new selection", + "switchBusy": "Profile switch is already in progress", "batchDeleted": "Selected profiles deleted successfully" }, "notices": { diff --git a/src/locales/zh/profiles.json b/src/locales/zh/profiles.json index ca4607f55..0bd22903f 100644 --- a/src/locales/zh/profiles.json +++ b/src/locales/zh/profiles.json @@ -37,7 +37,7 @@ "importSuccess": "订阅已成功导入,如未显示请重启应用", "profileSwitched": "订阅已切换", "profileReactivated": "订阅已激活", - "switchInterrupted": "订阅切换被新选择中断", + "switchBusy": "正在切换订阅,请稍后重试", "batchDeleted": "选中的订阅已成功删除" }, "notices": { diff --git a/src/locales/zhtw/profiles.json b/src/locales/zhtw/profiles.json index 4ab505c2c..b282ecb72 100644 --- a/src/locales/zhtw/profiles.json +++ b/src/locales/zhtw/profiles.json @@ -37,7 +37,7 @@ "importSuccess": "Profile imported successfully, please restart if not visible", "profileSwitched": "訂閱已切換", "profileReactivated": "訂閱已啟用", - "switchInterrupted": "配置切換被新的選擇中斷", + "switchBusy": "正在切換配置,請稍後重試", "batchDeleted": "選取的訂閱已成功刪除" }, "notices": { diff --git a/src/pages/profiles.tsx b/src/pages/profiles.tsx index ad4bf6adc..0e8179c0d 100644 --- a/src/pages/profiles.tsx +++ b/src/pages/profiles.tsx @@ -26,14 +26,7 @@ import { readText } from '@tauri-apps/plugin-clipboard-manager' import { readTextFile } from '@tauri-apps/plugin-fs' import { useLockFn } from 'ahooks' import { throttle } from 'lodash-es' -import { - useCallback, - useEffect, - useMemo, - useRef, - useState, - type RefObject, -} from 'react' +import { useCallback, useEffect, useMemo, useRef, useState } from 'react' import { useTranslation } from 'react-i18next' import { useLocation } from 'react-router' import { closeAllConnections } from 'tauri-plugin-mihomo-api' @@ -78,6 +71,13 @@ import { debugLog } from '@/utils/debug' // 与 src-tauri/src/main.rs 的 worker_limit 上限(8)保持一致,避免前后端更新风暴不对齐 const PROFILE_UPDATE_WORKER_LIMIT = 8 +const PROFILE_SWITCH_LOADING_DELAY = 400 + +interface ProfileSwitchRequest { + profile: string + notifySuccess: boolean + force: boolean +} // 记录profile切换状态 const debugProfileSwitch = (action: string, profile: string, extra?: any) => { @@ -85,35 +85,6 @@ const debugProfileSwitch = (action: string, profile: string, extra?: any) => { debugLog(`[Profile-Debug][${timestamp}] ${action}: ${profile}`, extra || '') } -// 检查请求是否已过期 -const isRequestOutdated = ( - currentSequence: number, - requestSequenceRef: RefObject, - profile: string, -) => { - if (currentSequence !== requestSequenceRef.current) { - debugProfileSwitch( - 'REQUEST_OUTDATED', - profile, - `当前序列号: ${currentSequence}, 最新序列号: ${requestSequenceRef.current}`, - ) - return true - } - return false -} - -// 检查是否被中断 -const isOperationAborted = ( - abortController: AbortController, - profile: string, -) => { - if (abortController.signal.aborted) { - debugProfileSwitch('OPERATION_ABORTED', profile) - return true - } - return false -} - const ProfilePage = () => { const { t } = useTranslation() const location = useLocation() @@ -121,6 +92,10 @@ const ProfilePage = () => { const [url, setUrl] = useState('') const [disabled, setDisabled] = useState(false) const [activatings, setActivatings] = useState([]) + const [switchTarget, setSwitchTarget] = useState(null) + const [visibleSwitchingProfile, setVisibleSwitchingProfile] = useState< + string | null + >(null) const [loading, setLoading] = useState(false) // Batch selection states @@ -129,57 +104,15 @@ const ProfilePage = () => { () => new Set(), ) - // 防止重复切换 - const switchingProfileRef = useRef(null) - - // 支持中断当前切换操作 - const abortControllerRef = useRef(null) - - // 只处理最新的切换请求 - const requestSequenceRef = useRef(0) - - // 待处理请求跟踪,取消排队的请求 - const pendingRequestRef = useRef | null>(null) - - // 处理profile切换中断 - const handleProfileInterrupt = useCallback( - (previousSwitching: string, newProfile: string) => { - debugProfileSwitch( - 'INTERRUPT_PREVIOUS', - previousSwitching, - `被 ${newProfile} 中断`, - ) - - if (abortControllerRef.current) { - abortControllerRef.current.abort() - debugProfileSwitch('ABORT_CONTROLLER_TRIGGERED', previousSwitching) - } - - if (pendingRequestRef.current) { - debugProfileSwitch('CANCEL_PENDING_REQUEST', previousSwitching) - } - - setActivatings((prev) => prev.filter((id) => id !== previousSwitching)) - showNotice.info( - 'profiles.page.feedback.notifications.switchInterrupted', - `${previousSwitching} → ${newProfile}`, - 3000, - ) - }, - [], - ) - - // 清理切换状态 - const cleanupSwitchState = useCallback( - (profile: string, sequence: number) => { - setActivatings((prev) => prev.filter((id) => id !== profile)) - switchingProfileRef.current = null - abortControllerRef.current = null - pendingRequestRef.current = null - debugProfileSwitch('SWITCH_END', profile, `序列号: ${sequence}`) - }, - [], + // Profile 切换在前端串行执行;队列中只保留用户最后一次选择。 + const latestSwitchTargetRef = useRef(null) + const queuedSwitchRef = useRef(null) + const switchRunnerRef = useRef | null>(null) + const switchLoadingTimerRef = useRef | null>( + null, ) + const currentProfileRef = useRef(undefined) + const profilePageMountedRef = useRef(true) const sensors = useSensors( useSensor(PointerSensor, { activationConstraint: { distance: 8 }, @@ -198,6 +131,10 @@ const ProfilePage = () => { isStale, } = useProfiles() + useEffect(() => { + currentProfileRef.current = profiles.current + }, [profiles]) + useEffect(() => { const handleFileDrop = async () => { const unlisten = await addListener( @@ -267,10 +204,13 @@ const ProfilePage = () => { } }) - const { data: chainLogs = {}, refetch: mutateLogs } = useQuery({ + const { data: chainLogs = {}, refetch: refetchLogs } = useQuery({ queryKey: ['getRuntimeLogs'], queryFn: getRuntimeLogs, }) + const refetchLogsRef = useRef(refetchLogs) + refetchLogsRef.current = refetchLogs + const mutateLogs = useCallback(() => refetchLogsRef.current(), []) const viewerRef = useRef(null) const configRef = useRef(null) @@ -396,156 +336,147 @@ const ProfilePage = () => { } } - const activateProfile = useCallback( - async (profile: string, notifySuccess: boolean) => { - if (profiles.current === profile && !notifySuccess) { - debugLog(`[Profile] 目标profile ${profile} 已经是当前配置,跳过切换`) + const executeProfileSwitch = useCallback( + async ({ profile, notifySuccess, force }: ProfileSwitchRequest) => { + if (!force && currentProfileRef.current === profile) { + debugProfileSwitch('ALREADY_CURRENT_IGNORED', profile) return } - const currentSequence = ++requestSequenceRef.current - debugProfileSwitch('NEW_REQUEST', profile, `序列号: ${currentSequence}`) - - // 处理中断逻辑 - const previousSwitching = switchingProfileRef.current - if (previousSwitching && previousSwitching !== profile) { - handleProfileInterrupt(previousSwitching, profile) - } - - // 防止重复切换同一个profile - if (switchingProfileRef.current === profile) { - debugProfileSwitch('DUPLICATE_SWITCH_BLOCKED', profile) - return - } - - // 初始化切换状态 - switchingProfileRef.current = profile - debugProfileSwitch('SWITCH_START', profile, `序列号: ${currentSequence}`) - - const currentAbortController = new AbortController() - abortControllerRef.current = currentAbortController - - setActivatings((prev) => { - if (prev.includes(profile)) return prev - return [...prev, profile] - }) + debugProfileSwitch('SWITCH_START', profile) try { - debugLog(`[Profile] 开始切换到: ${profile},序列号: ${currentSequence}`) - - // 检查请求有效性 - if ( - isRequestOutdated(currentSequence, requestSequenceRef, profile) || - isOperationAborted(currentAbortController, profile) - ) { - return - } - - // 执行切换请求 - const requestPromise = patchProfiles( - { current: profile }, - currentAbortController.signal, - { - deferRefreshOnSuccess: true, - }, - ) - pendingRequestRef.current = requestPromise - - const success = await requestPromise - - if (pendingRequestRef.current === requestPromise) { - pendingRequestRef.current = null - } - - // 再次检查有效性 - if ( - isRequestOutdated(currentSequence, requestSequenceRef, profile) || - isOperationAborted(currentAbortController, profile) - ) { - return - } - - // 完成切换 - await mutateLogs() - closeAllConnections() - - if (notifySuccess && success) { - showNotice.success( - 'profiles.page.feedback.notifications.profileSwitched', - 1000, + const outcome = await patchProfiles({ current: profile }) + if (outcome.status === 'busy') { + debugProfileSwitch('SWITCH_BUSY', profile) + showNotice.info( + 'profiles.page.feedback.notifications.switchBusy', + 2000, ) - } - - debugLog( - `[Profile] 切换到 ${profile} 完成,序列号: ${currentSequence},开始后台处理`, - ) - } catch (err: any) { - if (pendingRequestRef.current) { - pendingRequestRef.current = null - } - - // 检查是否因为中断或过期而出错 - if ( - isOperationAborted(currentAbortController, profile) || - isRequestOutdated(currentSequence, requestSequenceRef, profile) - ) { return } + if (outcome.status === 'valid') { + currentProfileRef.current = profile + void mutateLogs().catch(() => {}) + void closeAllConnections().catch(() => {}) + + if ( + notifySuccess && + latestSwitchTargetRef.current === profile && + queuedSwitchRef.current === null + ) { + showNotice.success( + 'profiles.page.feedback.notifications.profileSwitched', + 1000, + ) + } + debugProfileSwitch('SWITCH_SUCCESS', profile) + } else { + debugProfileSwitch('SWITCH_REJECTED', profile, outcome) + } + } catch (err: any) { console.error(`[Profile] 切换失败:`, err) showNotice.error(err, 4000) } finally { - // 只有当前profile仍然是正在切换的profile且序列号匹配时才清理状态 - if ( - switchingProfileRef.current === profile && - currentSequence === requestSequenceRef.current - ) { - cleanupSwitchState(profile, currentSequence) - } else { - debugProfileSwitch( - 'CLEANUP_SKIPPED', - profile, - `序列号不匹配或已被接管: ${currentSequence} vs ${requestSequenceRef.current}`, - ) - } + debugProfileSwitch('SWITCH_END', profile) } }, - [ - profiles, - patchProfiles, - mutateLogs, - handleProfileInterrupt, - cleanupSwitchState, - ], + [mutateLogs, patchProfiles], ) - const onSelect = async (current: string, force: boolean) => { - // 阻止重复点击或已激活的profile - if (switchingProfileRef.current === current) { - debugProfileSwitch('DUPLICATE_CLICK_IGNORED', current) - return - } - if (!force && current === profiles.current) { - debugProfileSwitch('ALREADY_CURRENT_IGNORED', current) - return + const runProfileSwitchQueue = useCallback(async () => { + while (profilePageMountedRef.current && queuedSwitchRef.current) { + const request = queuedSwitchRef.current + queuedSwitchRef.current = null + await executeProfileSwitch(request) } + }, [executeProfileSwitch]) - await activateProfile(current, true) + const activateProfile = useCallback( + (profile: string, notifySuccess: boolean, force = false) => { + if (!profilePageMountedRef.current) return Promise.resolve() + + if ( + !force && + currentProfileRef.current === profile && + switchRunnerRef.current === null + ) { + debugProfileSwitch('ALREADY_CURRENT_IGNORED', profile) + return Promise.resolve() + } + + if ( + latestSwitchTargetRef.current === profile && + switchRunnerRef.current + ) { + debugProfileSwitch('DUPLICATE_SWITCH_IGNORED', profile) + return switchRunnerRef.current + } + + latestSwitchTargetRef.current = profile + queuedSwitchRef.current = { profile, notifySuccess, force } + setSwitchTarget(profile) + setVisibleSwitchingProfile(null) + if (switchLoadingTimerRef.current) { + window.clearTimeout(switchLoadingTimerRef.current) + } + switchLoadingTimerRef.current = window.setTimeout(() => { + if ( + profilePageMountedRef.current && + latestSwitchTargetRef.current === profile + ) { + setVisibleSwitchingProfile(profile) + } + }, PROFILE_SWITCH_LOADING_DELAY) + + if (switchRunnerRef.current) { + debugProfileSwitch('SWITCH_QUEUED', profile) + return switchRunnerRef.current + } + + const runner = runProfileSwitchQueue().finally(() => { + if (switchRunnerRef.current === runner) { + switchRunnerRef.current = null + latestSwitchTargetRef.current = null + if (switchLoadingTimerRef.current) { + window.clearTimeout(switchLoadingTimerRef.current) + switchLoadingTimerRef.current = null + } + if (profilePageMountedRef.current) { + setSwitchTarget(null) + setVisibleSwitchingProfile(null) + } + } + }) + switchRunnerRef.current = runner + return runner + }, + [runProfileSwitchQueue], + ) + + const onSelect = async (profile: string, force: boolean) => { + await activateProfile(profile, true, force) } useEffect(() => { - ;(async () => { + let cancelled = false + void (async () => { if (current) { - mutateProfiles() + await mutateProfiles() + if (cancelled) return await activateProfile(current, false) } })() + return () => { + cancelled = true + } }, [current, activateProfile, mutateProfiles]) const onEnhance = useLockFn(async (notifySuccess: boolean) => { - if (switchingProfileRef.current) { + if (switchRunnerRef.current) { debugLog( - `[Profile] 有profile正在切换中(${switchingProfileRef.current}),跳过enhance操作`, + `[Profile] 有profile正在切换中(${latestSwitchTargetRef.current}),跳过enhance操作`, ) return } @@ -565,10 +496,7 @@ const ProfilePage = () => { } catch (err: any) { showNotice.error(err, 3000) } finally { - // 保留正在切换的profile,清除其他状态 - setActivatings((prev) => - prev.filter((id) => id === switchingProfileRef.current), - ) + setActivatings([]) } }) @@ -747,12 +675,16 @@ const ProfilePage = () => { ? 'rgba(0, 0, 0, 0.06)' : 'rgba(255, 255, 255, 0.06)' - // 组件卸载时清理中断控制器 + // 卸载后不再执行尚未发送的切换意图。 useEffect(() => { + profilePageMountedRef.current = true return () => { - if (abortControllerRef.current) { - abortControllerRef.current.abort() - debugProfileSwitch('COMPONENT_UNMOUNT_CLEANUP', 'all') + profilePageMountedRef.current = false + queuedSwitchRef.current = null + latestSwitchTargetRef.current = null + if (switchLoadingTimerRef.current) { + window.clearTimeout(switchLoadingTimerRef.current) + switchLoadingTimerRef.current = null } } }, []) @@ -965,8 +897,11 @@ const ProfilePage = () => { onSelect(item.uid, f)} diff --git a/src/providers/app-data-provider.tsx b/src/providers/app-data-provider.tsx index 06fc86ee3..19f6fe4fe 100644 --- a/src/providers/app-data-provider.tsx +++ b/src/providers/app-data-provider.tsx @@ -124,7 +124,8 @@ export const AppDataProvider = ({ useEffect(() => { let lastProfileId: string | null = null - let lastUpdateTime = 0 + let lastProfileUpdateTime = 0 + let lastProxyUpdateTime = 0 const refreshThrottle = 800 const cleanupFns: Array<() => void> = [] @@ -133,25 +134,19 @@ export const AppDataProvider = ({ const now = Date.now() if ( lastProfileId === newProfileId && - now - lastUpdateTime < refreshThrottle + now - lastProfileUpdateTime < refreshThrottle ) { return } lastProfileId = newProfileId - lastUpdateTime = now - void Promise.allSettled([ - revalidateQueries([['getProfiles']]), - refreshProxy(), - refreshProxyProviders(), - refreshRules(), - refreshRuleProviders(), - ]) + lastProfileUpdateTime = now + void revalidateQueries([['getProfiles']]) } const handleRefreshProxy = () => { const now = Date.now() - if (now - lastUpdateTime <= refreshThrottle) return - lastUpdateTime = now + if (now - lastProxyUpdateTime <= refreshThrottle) return + lastProxyUpdateTime = now refreshProxy().catch(() => {}) } @@ -202,7 +197,7 @@ export const AppDataProvider = ({ } }) } - }, [refreshProxy, refreshProxyProviders, refreshRules, refreshRuleProviders]) + }, [refreshProxy]) const refreshAll = useCallback(async () => { await Promise.all([ diff --git a/src/services/cmds.ts b/src/services/cmds.ts index 54d9fd00c..cb70dbe84 100644 --- a/src/services/cmds.ts +++ b/src/services/cmds.ts @@ -20,10 +20,7 @@ export async function enhanceProfiles() { } export async function patchProfilesConfig(profiles: IProfilesConfig) { - return ( - (await invoke('patch_profiles_config', { profiles })) - .status === 'valid' - ) + return invoke('patch_profiles_config', { profiles }) } export async function createProfile( diff --git a/src/services/query-client.ts b/src/services/query-client.ts index 8e47ea67c..ab71735b4 100644 --- a/src/services/query-client.ts +++ b/src/services/query-client.ts @@ -6,6 +6,10 @@ import useSWR, { } from 'swr' type QueryKey = string | readonly unknown[] +type QueryDataUpdater = + | T + | undefined + | ((current: T | undefined) => T | undefined) type QueryOptions = { queryKey: QueryKey @@ -53,18 +57,24 @@ export const getCacheData = (queryKey: QueryKey): T | undefined => { return queryCache.get(serializeQueryKey(queryKey)) as T | undefined } -export const setCacheData = ( +const updateCachedData = ( queryKey: QueryKey, - updaterOrData: T | undefined | ((current: T | undefined) => T | undefined), + updaterOrData: QueryDataUpdater, ) => { const current = getCacheData(queryKey) const next = typeof updaterOrData === 'function' ? (updaterOrData as (current: T | undefined) => T | undefined)(current) : updaterOrData - setCachedData(queryKey, next) + return next +} +export const setCacheData = ( + queryKey: QueryKey, + updaterOrData: QueryDataUpdater, +) => { + const next = updateCachedData(queryKey, updaterOrData) void swrMutate(queryKey, next, { populateCache: true, revalidate: false, @@ -72,6 +82,18 @@ export const setCacheData = ( return next } +export const setCacheDataAsync = async ( + queryKey: QueryKey, + updaterOrData: QueryDataUpdater, +) => { + const next = updateCachedData(queryKey, updaterOrData) + await swrMutate(queryKey, next, { + populateCache: true, + revalidate: false, + }) + return next +} + export const revalidateQuery = async (queryKey: QueryKey) => { const data = await swrMutate(queryKey) if (data !== undefined) { diff --git a/src/types/generated/i18n-keys.ts b/src/types/generated/i18n-keys.ts index cbfa60641..41a00f852 100644 --- a/src/types/generated/i18n-keys.ts +++ b/src/types/generated/i18n-keys.ts @@ -133,7 +133,7 @@ export const translationKeys = [ 'profiles.page.feedback.notifications.importSuccess', 'profiles.page.feedback.notifications.profileSwitched', 'profiles.page.feedback.notifications.profileReactivated', - 'profiles.page.feedback.notifications.switchInterrupted', + 'profiles.page.feedback.notifications.switchBusy', 'profiles.page.feedback.notifications.batchDeleted', 'profiles.page.feedback.notices.forceRefreshCompleted', 'profiles.page.feedback.notices.emergencyRefreshFailed', diff --git a/src/types/generated/i18n-resources.ts b/src/types/generated/i18n-resources.ts index 6ff3bca11..cd3b3dd59 100644 --- a/src/types/generated/i18n-resources.ts +++ b/src/types/generated/i18n-resources.ts @@ -379,7 +379,7 @@ export interface TranslationResources { importSuccess: string profileReactivated: string profileSwitched: string - switchInterrupted: string + switchBusy: string } } importForm: {