mirror of
https://github.com/clash-verge-rev/clash-verge-rev.git
synced 2026-11-23 04:42:08 +08:00
perf: streamline profile switching
This commit is contained in:
@@ -213,16 +213,8 @@ async fn restore_previous_profile(prev_profile: &String) -> CmdResult<()> {
|
||||
|
||||
async fn handle_success(current_value: Option<&String>) -> CmdResult<ValidationOutcome> {
|
||||
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}");
|
||||
|
||||
@@ -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<String, String>,
|
||||
) -> 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<String, String>,
|
||||
generation: u64,
|
||||
) -> Option<usize> {
|
||||
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()),
|
||||
]
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
+34
-34
@@ -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<IProfilesConfig>,
|
||||
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<IProfilesConfig>) => {
|
||||
try {
|
||||
const outcome = await patchProfilesConfig(value)
|
||||
|
||||
if (signal?.aborted) {
|
||||
throw new DOMException('Operation was aborted', 'AbortError')
|
||||
}
|
||||
if (outcome.status === 'valid') {
|
||||
await setCacheDataAsync<IProfilesConfig>(
|
||||
['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<IProfileItem>) => {
|
||||
if (profiles?.current) {
|
||||
await patchProfile(profiles.current, value)
|
||||
mutateProfiles()
|
||||
}
|
||||
}
|
||||
const patchCurrent = useCallback(
|
||||
async (value: Partial<IProfileItem>) => {
|
||||
if (profiles?.current) {
|
||||
await patchProfile(profiles.current, value)
|
||||
void mutateProfiles()
|
||||
}
|
||||
},
|
||||
[mutateProfiles, profiles],
|
||||
)
|
||||
|
||||
return {
|
||||
profiles,
|
||||
|
||||
@@ -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": {
|
||||
|
||||
@@ -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": {
|
||||
|
||||
@@ -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": {
|
||||
|
||||
@@ -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": {
|
||||
|
||||
@@ -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": {
|
||||
|
||||
@@ -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": {
|
||||
|
||||
@@ -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": {
|
||||
|
||||
@@ -37,7 +37,7 @@
|
||||
"importSuccess": "프로필을 성공적으로 가져왔습니다. 보이지 않으면 재시작하세요",
|
||||
"profileSwitched": "프로필 전환됨",
|
||||
"profileReactivated": "프로필 재활성화됨",
|
||||
"switchInterrupted": "새 선택으로 인해 프로필 전환이 중단되었습니다",
|
||||
"switchBusy": "프로필 전환이 이미 진행 중입니다",
|
||||
"batchDeleted": "선택한 프로필이 삭제되었습니다"
|
||||
},
|
||||
"notices": {
|
||||
|
||||
@@ -37,7 +37,7 @@
|
||||
"importSuccess": "Профиль успешно импортирован. Перезапустите приложение, если он не появился",
|
||||
"profileSwitched": "Профиль переключён",
|
||||
"profileReactivated": "Профиль перезапущен",
|
||||
"switchInterrupted": "Переключение профиля прервано новым выбором",
|
||||
"switchBusy": "Переключение профиля уже выполняется",
|
||||
"batchDeleted": "Выбранные профили удалены"
|
||||
},
|
||||
"notices": {
|
||||
|
||||
@@ -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": {
|
||||
|
||||
@@ -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": {
|
||||
|
||||
@@ -37,7 +37,7 @@
|
||||
"importSuccess": "订阅已成功导入,如未显示请重启应用",
|
||||
"profileSwitched": "订阅已切换",
|
||||
"profileReactivated": "订阅已激活",
|
||||
"switchInterrupted": "订阅切换被新选择中断",
|
||||
"switchBusy": "正在切换订阅,请稍后重试",
|
||||
"batchDeleted": "选中的订阅已成功删除"
|
||||
},
|
||||
"notices": {
|
||||
|
||||
@@ -37,7 +37,7 @@
|
||||
"importSuccess": "Profile imported successfully, please restart if not visible",
|
||||
"profileSwitched": "訂閱已切換",
|
||||
"profileReactivated": "訂閱已啟用",
|
||||
"switchInterrupted": "配置切換被新的選擇中斷",
|
||||
"switchBusy": "正在切換配置,請稍後重試",
|
||||
"batchDeleted": "選取的訂閱已成功刪除"
|
||||
},
|
||||
"notices": {
|
||||
|
||||
+154
-219
@@ -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<number>,
|
||||
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<string[]>([])
|
||||
const [switchTarget, setSwitchTarget] = useState<string | null>(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<string | null>(null)
|
||||
|
||||
// 支持中断当前切换操作
|
||||
const abortControllerRef = useRef<AbortController | null>(null)
|
||||
|
||||
// 只处理最新的切换请求
|
||||
const requestSequenceRef = useRef<number>(0)
|
||||
|
||||
// 待处理请求跟踪,取消排队的请求
|
||||
const pendingRequestRef = useRef<Promise<any> | 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<string | null>(null)
|
||||
const queuedSwitchRef = useRef<ProfileSwitchRequest | null>(null)
|
||||
const switchRunnerRef = useRef<Promise<void> | null>(null)
|
||||
const switchLoadingTimerRef = useRef<ReturnType<typeof setTimeout> | null>(
|
||||
null,
|
||||
)
|
||||
const currentProfileRef = useRef<string | undefined>(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<ProfileViewerRef>(null)
|
||||
const configRef = useRef<DialogRef>(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 = () => {
|
||||
<Grid size={{ xs: 12, sm: 6, md: 4, lg: 3 }} key={item.file}>
|
||||
<ProfileItem
|
||||
id={item.uid}
|
||||
selected={profiles.current === item.uid}
|
||||
activating={activatings.includes(item.uid)}
|
||||
selected={(switchTarget ?? profiles.current) === item.uid}
|
||||
activating={
|
||||
activatings.includes(item.uid) ||
|
||||
visibleSwitchingProfile === item.uid
|
||||
}
|
||||
itemData={item}
|
||||
mutateProfiles={mutateProfiles}
|
||||
onSelect={(f) => onSelect(item.uid, f)}
|
||||
|
||||
@@ -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([
|
||||
|
||||
@@ -20,10 +20,7 @@ export async function enhanceProfiles() {
|
||||
}
|
||||
|
||||
export async function patchProfilesConfig(profiles: IProfilesConfig) {
|
||||
return (
|
||||
(await invoke<ValidationOutcome>('patch_profiles_config', { profiles }))
|
||||
.status === 'valid'
|
||||
)
|
||||
return invoke<ValidationOutcome>('patch_profiles_config', { profiles })
|
||||
}
|
||||
|
||||
export async function createProfile(
|
||||
|
||||
@@ -6,6 +6,10 @@ import useSWR, {
|
||||
} from 'swr'
|
||||
|
||||
type QueryKey = string | readonly unknown[]
|
||||
type QueryDataUpdater<T> =
|
||||
| T
|
||||
| undefined
|
||||
| ((current: T | undefined) => T | undefined)
|
||||
|
||||
type QueryOptions<T> = {
|
||||
queryKey: QueryKey
|
||||
@@ -53,18 +57,24 @@ export const getCacheData = <T>(queryKey: QueryKey): T | undefined => {
|
||||
return queryCache.get(serializeQueryKey(queryKey)) as T | undefined
|
||||
}
|
||||
|
||||
export const setCacheData = <T>(
|
||||
const updateCachedData = <T>(
|
||||
queryKey: QueryKey,
|
||||
updaterOrData: T | undefined | ((current: T | undefined) => T | undefined),
|
||||
updaterOrData: QueryDataUpdater<T>,
|
||||
) => {
|
||||
const current = getCacheData<T>(queryKey)
|
||||
const next =
|
||||
typeof updaterOrData === 'function'
|
||||
? (updaterOrData as (current: T | undefined) => T | undefined)(current)
|
||||
: updaterOrData
|
||||
|
||||
setCachedData(queryKey, next)
|
||||
return next
|
||||
}
|
||||
|
||||
export const setCacheData = <T>(
|
||||
queryKey: QueryKey,
|
||||
updaterOrData: QueryDataUpdater<T>,
|
||||
) => {
|
||||
const next = updateCachedData(queryKey, updaterOrData)
|
||||
void swrMutate(queryKey, next, {
|
||||
populateCache: true,
|
||||
revalidate: false,
|
||||
@@ -72,6 +82,18 @@ export const setCacheData = <T>(
|
||||
return next
|
||||
}
|
||||
|
||||
export const setCacheDataAsync = async <T>(
|
||||
queryKey: QueryKey,
|
||||
updaterOrData: QueryDataUpdater<T>,
|
||||
) => {
|
||||
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) {
|
||||
|
||||
@@ -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',
|
||||
|
||||
@@ -379,7 +379,7 @@ export interface TranslationResources {
|
||||
importSuccess: string
|
||||
profileReactivated: string
|
||||
profileSwitched: string
|
||||
switchInterrupted: string
|
||||
switchBusy: string
|
||||
}
|
||||
}
|
||||
importForm: {
|
||||
|
||||
Reference in New Issue
Block a user