diff --git a/Changelog.md b/Changelog.md index 3d500e11d..81b5d54a8 100644 --- a/Changelog.md +++ b/Changelog.md @@ -28,6 +28,7 @@
🐞 修复问题 +- 优化订阅恢复失败提示,显示受影响的订阅名称 - 修复「外部控制器」复制成功的提示一闪而过 - 修复订阅的规则、代理组、节点编辑器快速连续操作时条目可能重复或错位 - 修复检测更新后又发布新版时,应用内更新失败 diff --git a/crates/clash-verge-i18n/build.rs b/crates/clash-verge-i18n/build.rs new file mode 100644 index 000000000..27e2f784b --- /dev/null +++ b/crates/clash-verge-i18n/build.rs @@ -0,0 +1,3 @@ +fn main() { + println!("cargo::rerun-if-changed=locales"); +} diff --git a/crates/clash-verge-i18n/locales/ar.yml b/crates/clash-verge-i18n/locales/ar.yml index 4476f4da3..ecf25c0bf 100644 --- a/crates/clash-verge-i18n/locales/ar.yml +++ b/crates/clash-verge-i18n/locales/ar.yml @@ -85,3 +85,6 @@ tray: systemProxy: وكيل النظام tun: TUN profile: ملف تعريفي +profileRecovery: + named: يجب استعادة الاشتراك «{name}». راجع سجل التطبيق للاطلاع على التفاصيل. + unknown: يجب استعادة أحد الاشتراكات، لكن تعذّر تحديده. راجع سجل التطبيق للاطلاع على التفاصيل. diff --git a/crates/clash-verge-i18n/locales/de.yml b/crates/clash-verge-i18n/locales/de.yml index 580e7ddd7..d453725f2 100644 --- a/crates/clash-verge-i18n/locales/de.yml +++ b/crates/clash-verge-i18n/locales/de.yml @@ -85,3 +85,6 @@ tray: systemProxy: Systemproxy tun: TUN profile: Profil +profileRecovery: + named: Das Abonnement „{name}“ muss wiederhergestellt werden. Details stehen im Anwendungsprotokoll. + unknown: Ein Abonnement muss wiederhergestellt werden, konnte aber nicht identifiziert werden. Details stehen im Anwendungsprotokoll. diff --git a/crates/clash-verge-i18n/locales/en.yml b/crates/clash-verge-i18n/locales/en.yml index ecad0ddf3..bfbb1bd2e 100644 --- a/crates/clash-verge-i18n/locales/en.yml +++ b/crates/clash-verge-i18n/locales/en.yml @@ -85,3 +85,6 @@ tray: systemProxy: System Proxy tun: TUN profile: Profile +profileRecovery: + named: Subscription “{name}” needs recovery. See the application log for details. + unknown: Subscription recovery is required. The affected subscription could not be identified. See the application log for details. diff --git a/crates/clash-verge-i18n/locales/es.yml b/crates/clash-verge-i18n/locales/es.yml index 76ecd7e96..62ff389b2 100644 --- a/crates/clash-verge-i18n/locales/es.yml +++ b/crates/clash-verge-i18n/locales/es.yml @@ -85,3 +85,6 @@ tray: systemProxy: Proxy del sistema tun: TUN profile: Perfil +profileRecovery: + named: Hay que recuperar la suscripción «{name}». Consulta el registro de la aplicación para más detalles. + unknown: Hay que recuperar una suscripción, pero no se pudo identificar cuál. Consulta el registro de la aplicación para más detalles. diff --git a/crates/clash-verge-i18n/locales/fa.yml b/crates/clash-verge-i18n/locales/fa.yml index b21404682..1bbf8be84 100644 --- a/crates/clash-verge-i18n/locales/fa.yml +++ b/crates/clash-verge-i18n/locales/fa.yml @@ -85,3 +85,6 @@ tray: systemProxy: پروکسی سیستم tun: TUN profile: پروفایل +profileRecovery: + named: اشتراک «{name}» باید بازیابی شود. برای جزئیات، گزارش برنامه را ببینید. + unknown: بازیابی اشتراک لازم است، اما اشتراک موردنظر شناسایی نشد. برای جزئیات، گزارش برنامه را ببینید. diff --git a/crates/clash-verge-i18n/locales/id.yml b/crates/clash-verge-i18n/locales/id.yml index cf2750a26..eb557dece 100644 --- a/crates/clash-verge-i18n/locales/id.yml +++ b/crates/clash-verge-i18n/locales/id.yml @@ -85,3 +85,6 @@ tray: systemProxy: Proksi Sistem tun: TUN profile: Profil +profileRecovery: + named: Langganan “{name}” perlu dipulihkan. Lihat log aplikasi untuk detailnya. + unknown: Langganan perlu dipulihkan, tetapi langganan yang terdampak tidak dapat diidentifikasi. Lihat log aplikasi untuk detailnya. diff --git a/crates/clash-verge-i18n/locales/jp.yml b/crates/clash-verge-i18n/locales/jp.yml index 2ca38403c..1e3a146ee 100644 --- a/crates/clash-verge-i18n/locales/jp.yml +++ b/crates/clash-verge-i18n/locales/jp.yml @@ -85,3 +85,6 @@ tray: systemProxy: システムプロキシ tun: TUN profile: プロファイル +profileRecovery: + named: サブスクリプション「{name}」の復旧が必要です。詳細はアプリのログを確認してください。 + unknown: サブスクリプションの復旧が必要ですが、対象を特定できません。詳細はアプリのログを確認してください。 diff --git a/crates/clash-verge-i18n/locales/ko.yml b/crates/clash-verge-i18n/locales/ko.yml index 900d7d5ad..61514e621 100644 --- a/crates/clash-verge-i18n/locales/ko.yml +++ b/crates/clash-verge-i18n/locales/ko.yml @@ -85,3 +85,6 @@ tray: systemProxy: 시스템 프록시 tun: TUN profile: 프로필 +profileRecovery: + named: “{name}” 구독을 복구해야 합니다. 자세한 내용은 앱 로그를 확인하세요. + unknown: 구독을 복구해야 하지만 해당 구독을 식별할 수 없습니다. 자세한 내용은 앱 로그를 확인하세요. diff --git a/crates/clash-verge-i18n/locales/pt.yml b/crates/clash-verge-i18n/locales/pt.yml index 8daacfafd..038fc719e 100644 --- a/crates/clash-verge-i18n/locales/pt.yml +++ b/crates/clash-verge-i18n/locales/pt.yml @@ -85,3 +85,6 @@ tray: systemProxy: Proxy do sistema tun: TUN profile: Perfil +profileRecovery: + named: É necessário recuperar a assinatura “{name}”. Consulte o registro do aplicativo para mais detalhes. + unknown: É necessário recuperar uma assinatura, mas não foi possível identificá-la. Consulte o registro do aplicativo para mais detalhes. diff --git a/crates/clash-verge-i18n/locales/ru.yml b/crates/clash-verge-i18n/locales/ru.yml index 38b476763..1653e3780 100644 --- a/crates/clash-verge-i18n/locales/ru.yml +++ b/crates/clash-verge-i18n/locales/ru.yml @@ -85,3 +85,6 @@ tray: systemProxy: Системный прокси tun: TUN profile: Профиль +profileRecovery: + named: Подписку «{name}» нужно восстановить. Подробности в журнале приложения. + unknown: Не удалось определить, какую подписку необходимо восстановить. Подробности в журнале приложения. diff --git a/crates/clash-verge-i18n/locales/tr.yml b/crates/clash-verge-i18n/locales/tr.yml index 191267edc..faf67212a 100644 --- a/crates/clash-verge-i18n/locales/tr.yml +++ b/crates/clash-verge-i18n/locales/tr.yml @@ -85,3 +85,6 @@ tray: systemProxy: Sistem Vekil'i tun: TUN profile: Profil +profileRecovery: + named: “{name}” aboneliğinin kurtarılması gerekiyor. Ayrıntılar için uygulama günlüğüne bakın. + unknown: Kurtarılması gereken abonelik belirlenemedi. Ayrıntılar için uygulama günlüğüne bakın. diff --git a/crates/clash-verge-i18n/locales/tt.yml b/crates/clash-verge-i18n/locales/tt.yml index 1a9e4580b..0ac69f7c7 100644 --- a/crates/clash-verge-i18n/locales/tt.yml +++ b/crates/clash-verge-i18n/locales/tt.yml @@ -85,3 +85,6 @@ tray: systemProxy: Системалы прокси tun: TUN profile: Профиль +profileRecovery: + named: «{name}» язылуын торгызырга кирәк. Тулырак мәгълүмат кушымта журналында. + unknown: Кайсы язылуны торгызырга кирәклеген билгеләп булмады. Тулырак мәгълүмат кушымта журналында. diff --git a/crates/clash-verge-i18n/locales/zh.yml b/crates/clash-verge-i18n/locales/zh.yml index 020d8640d..1d655ff02 100644 --- a/crates/clash-verge-i18n/locales/zh.yml +++ b/crates/clash-verge-i18n/locales/zh.yml @@ -85,3 +85,6 @@ tray: systemProxy: 系统代理 tun: TUN profile: 订阅 +profileRecovery: + named: 订阅「{name}」需要恢复,详情请查看应用日志。 + unknown: 订阅需要恢复,但无法识别受影响的订阅。详情请查看应用日志。 diff --git a/crates/clash-verge-i18n/locales/zhtw.yml b/crates/clash-verge-i18n/locales/zhtw.yml index 9f7ac03b8..eac067665 100644 --- a/crates/clash-verge-i18n/locales/zhtw.yml +++ b/crates/clash-verge-i18n/locales/zhtw.yml @@ -85,3 +85,6 @@ tray: systemProxy: 系統代理 tun: 虛擬網路介面卡 profile: 訂閱 +profileRecovery: + named: 訂閱「{name}」需要復原,詳情請查看應用程式記錄。 + unknown: 訂閱需要復原,但無法識別受影響的訂閱。詳情請查看應用程式記錄。 diff --git a/crates/clash-verge-profile-store/src/error.rs b/crates/clash-verge-profile-store/src/error.rs index f6a19b462..d9a2a1241 100644 --- a/crates/clash-verge-profile-store/src/error.rs +++ b/crates/clash-verge-profile-store/src/error.rs @@ -2,6 +2,8 @@ use std::{io, path::PathBuf}; #[derive(Debug, thiserror::Error)] pub enum StoreError { + #[error("could not recover subscription “{name}”: {source}")] + NamedRecovery { name: String, source: Box }, #[error(transparent)] Io(#[from] io::Error), #[error("{operation} {}", path.display())] diff --git a/crates/clash-verge-profile-store/src/lib.rs b/crates/clash-verge-profile-store/src/lib.rs index f7b91f232..10e8e2ccd 100644 --- a/crates/clash-verge-profile-store/src/lib.rs +++ b/crates/clash-verge-profile-store/src/lib.rs @@ -85,12 +85,27 @@ impl Session { } #[cfg(windows)] if !platform::supports_redo(&root)? { - return Err(StoreError::UnsupportedVolume); + let source = StoreError::UnsupportedVolume; + return Err(match pending_refresh_name(&root) { + Some(name) => StoreError::NamedRecovery { + name, + source: Box::new(source), + }, + None => source, + }); } let lock = platform::open_lock(&root.join(RECOVERY_LOCK_NAME))?; lock.lock()?; let session = Self { root, _lock: lock }; - session.recover(checkpoint)?; + session + .recover(checkpoint) + .map_err(|error| match refresh_name(&session.root) { + Some(name) => StoreError::NamedRecovery { + name, + source: Box::new(error), + }, + None => error, + })?; Ok(session) } @@ -637,6 +652,34 @@ fn remove_file_if_exists(path: &Path) -> Result<()> { } } +fn refresh_name(root: &Path) -> Option { + let journal = root.join(RECOVERY_JOURNAL_NAME); + directory(&journal).ok()?; + let marker = match optional_regular(&journal.join(DECISION)).ok()? { + Some(_) => DECISION, + None => DECISION_NEXT, + }; + let decision = read_decision(&journal.join(marker)).ok()?; + let (index, _) = verified(&journal.join(INDEX_NEXT), decision.index_digest).ok()?; + let profiles: IProfiles = serde_yaml_ng::from_slice(&index).ok()?; + if body_filename(&profiles, &decision.uid).ok()? != decision.file { + return None; + } + let item = profiles.get_item(&decision.uid).ok()?; + item.name + .as_deref() + .filter(|name| !name.trim().is_empty()) + .map(str::to_owned) +} + +/// Identifies a pending transaction when this build or volume cannot replay it. +#[cfg(windows)] +pub fn pending_refresh_name(root: &Path) -> Option { + let lock = File::open(root.join(RECOVERY_LOCK_NAME)).ok()?; + lock.try_lock_shared().ok()?; + refresh_name(root) +} + /// Replays a saved decision before the application creates or loads its index. pub fn recover_pending(root: &Path) -> Result<()> { match fs::symlink_metadata(root.join(RECOVERY_JOURNAL_NAME)) { diff --git a/crates/clash-verge-profile-store/tests/legacy_refresh.rs b/crates/clash-verge-profile-store/tests/legacy_refresh.rs index 68f0657cc..989b0c75b 100644 --- a/crates/clash-verge-profile-store/tests/legacy_refresh.rs +++ b/crates/clash-verge-profile-store/tests/legacy_refresh.rs @@ -96,3 +96,33 @@ fn interrupted_creation_reverts_an_aliased_body() -> Result<(), clash_verge_prof )); Ok(()) } + +#[cfg(feature = "test-support")] +#[test] +fn recovery_identifies_the_interrupted_subscription_from_its_verified_index() +-> Result<(), clash_verge_profile_store::StoreError> { + use clash_verge_profile_store::{StoreError, recover_pending}; + + let home = tempfile::tempdir()?; + let root = home.path(); + fs::create_dir(root.join("profiles"))?; + let index = "current: other\nitems:\n- {uid: other, name: Home, type: remote, file: other.yaml}\n- {uid: opaque, name: 工作线路, type: remote, file: target.yaml}\n"; + fs::write(root.join("profiles.yaml"), index)?; + let candidate = serde_yaml_ng::from_str(index)?; + let outcome = Session::open(root)?.commit_observed("opaque", &candidate, b"new", &mut |phase| { + if phase == "decision-created" { + return Err(std::io::Error::other("interrupted").into()); + } + Ok(()) + }); + assert!(matches!(outcome, CommitOutcome::NeedsRecovery(_))); + fs::write(root.join("profiles/target.yaml"), b"changed outside the refresh")?; + let error = recover_pending(root).unwrap_err(); + assert!( + matches!(error, StoreError::NamedRecovery { name, source } if name == "工作线路" && matches!(*source, StoreError::LiveContentChanged(_))) + ); + let journal = root.join(clash_verge_profile_store::RECOVERY_JOURNAL_NAME); + fs::write(journal.join("index.next"), index.replace("工作线路", "Wrong"))?; + assert!(matches!(recover_pending(root), Err(StoreError::StagedChecksumMismatch))); + Ok(()) +} diff --git a/src-tauri/src/cmd/profile.rs b/src-tauri/src/cmd/profile.rs index 92936c299..a9be6e97a 100644 --- a/src-tauri/src/cmd/profile.rs +++ b/src-tauri/src/cmd/profile.rs @@ -34,11 +34,23 @@ fn profile_import_error(err: &anyhow::Error) -> std::string::String { format!("导入订阅失败: {err:#}") } +fn profile_command_error(error: anyhow::Error, fallback: Option<&str>) -> super::CommandFailure { + if error.is::() { + coded_error("PROFILE_RECOVERY_REQUIRED", format_args!("{error:#}")) + } else if let Some(code) = fallback { + coded_error(code, format_args!("{error:#}")) + } else { + super::CommandFailure::plain(error) + } +} + #[tauri::command] #[specta::specta] pub async fn get_profiles() -> CmdResult> { let draft = Config::profiles().await; - let _guard = crate::config::profile_storage::read().await.stringify_err()?; + let _guard = crate::config::profile_storage::read() + .await + .map_err(|error| profile_command_error(error, None))?; let data = draft.data_arc(); Ok(data) } @@ -146,7 +158,7 @@ pub async fn update_profile(index: std::string::String, option: Option = RwLock::const_new(()); static BLOCKED: Mutex> = Mutex::new(None); enum StorageBlock { - Transaction(String), + Transaction(RecoveryRequired), Restore(String), } +#[derive(Clone, Debug)] +pub(crate) struct RecoveryRequired(Option); + +impl std::fmt::Display for RecoveryRequired { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(&match self.0.as_deref() { + Some(name) => clash_verge_i18n::t!("profileRecovery.named", name = name), + None => clash_verge_i18n::t!("profileRecovery.unknown"), + }) + } +} + +impl std::error::Error for RecoveryRequired {} + pub(crate) fn check() -> Result<()> { match BLOCKED.lock().as_ref() { - Some(StorageBlock::Transaction(reason) | StorageBlock::Restore(reason)) => { - Err(anyhow!("Profile storage requires recovery before use: {reason}")) - } + Some(StorageBlock::Transaction(recovery)) => Err(recovery.clone().into()), + Some(StorageBlock::Restore(reason)) => Err(anyhow!("Profile storage requires recovery before use: {reason}")), None => Ok(()), } } -pub(crate) fn block(error: &anyhow::Error) { +pub(crate) fn block(name: Option<&str>, error: &anyhow::Error) -> anyhow::Error { + logging!(error, Type::Config, "Profile recovery required: {error:#}"); let mut blocked = BLOCKED.lock(); - if !matches!(*blocked, Some(StorageBlock::Transaction(_))) { - *blocked = Some(StorageBlock::Transaction(format!("{error:#}"))); + if let Some(StorageBlock::Transaction(recovery)) = blocked.as_ref() { + return recovery.clone().into(); + } + let recovery = RecoveryRequired(name.filter(|name| !name.trim().is_empty()).map(str::to_owned)); + *blocked = Some(StorageBlock::Transaction(recovery.clone())); + drop(blocked); + recovery.into() +} + +#[cfg(any(unix, all(windows, feature = "profile-store-windows")))] +fn block_store(error: clash_verge_profile_store::StoreError) -> anyhow::Error { + match error { + clash_verge_profile_store::StoreError::NamedRecovery { name, source } => { + block(Some(&name), &anyhow::Error::from(*source)) + } + error => block(None, &error.into()), } } @@ -38,7 +67,7 @@ pub(crate) async fn write_for_restore() -> Result<(RwLockWriteGuard<'static, ()> let guard = PROFILE_IO.write().await; let retry = match BLOCKED.lock().as_ref() { Some(StorageBlock::Transaction(reason)) => { - return Err(anyhow!("Profile storage requires recovery before use: {reason}")); + return Err(reason.clone().into()); } Some(StorageBlock::Restore(_)) => true, None => false, @@ -67,25 +96,21 @@ pub(crate) async fn write() -> Result> { pub(crate) async fn recover_at_startup() -> Result<()> { let _guard = write().await?; - let root = crate::utils::dirs::app_home_dir().inspect_err(block)?; - let result: Result<()> = async { - if !journal_exists(&root).await? { - return Ok(()); - } + let root = crate::utils::dirs::app_home_dir().map_err(|error| block(None, &error))?; + if !journal_exists(&root).await.map_err(|error| block(None, &error))? { + return Ok(()); + } + tokio::task::spawn_blocking(move || { #[cfg(any(unix, all(windows, feature = "profile-store-windows")))] - return tokio::task::spawn_blocking(move || clash_verge_profile_store::recover_pending(&root)) - .await? - .map_err(Into::into); - #[cfg(not(any(unix, all(windows, feature = "profile-store-windows"))))] - return Err(anyhow!( - "restore the pending profile transaction with redo support enabled" + return clash_verge_profile_store::recover_pending(&root).map_err(block_store); + #[cfg(all(windows, not(feature = "profile-store-windows")))] + return Err(block( + clash_verge_profile_store::pending_refresh_name(&root).as_deref(), + &anyhow!("restore the pending profile transaction with redo support enabled"), )); - } - .await; - if let Err(error) = &result { - block(error); - } - result + }) + .await + .map_err(|error| block(None, &error.into()))? } async fn journal_exists(root: &std::path::Path) -> Result { @@ -158,18 +183,20 @@ async fn commit_recoverable_refresh( if !supported { if journal_exists(&root).await? { let error = anyhow!("Profile refresh journal requires a supported NTFS volume"); - block(&error); - return Err(error); + return Err(block( + clash_verge_profile_store::pending_refresh_name(&root).as_deref(), + &error, + )); } write_legacy_refresh(&root, &uid, &candidate, body.as_bytes()).await?; return Ok(candidate); } } let result = tokio::task::spawn_blocking(move || { - let session = Session::open(&root).map_err(anyhow::Error::from).inspect_err(|error| { + let session = Session::open(&root).map_err(|error| { match std::fs::symlink_metadata(root.join(RECOVERY_JOURNAL_NAME)) { - Err(status) if status.kind() == std::io::ErrorKind::NotFound => {} - _ => block(error), + Err(status) if status.kind() == std::io::ErrorKind::NotFound => error.into(), + _ => block_store(error), } })?; let item = candidate.get_item(&uid)?; @@ -191,7 +218,7 @@ async fn commit_recoverable_refresh( match session.commit_refresh(&uid, &candidate, body.as_bytes()) { CommitOutcome::Committed => Ok(candidate), CommitOutcome::CommittedCleanupPending(error) => { - block(&error.into()); + let _ = block(item.name.as_deref(), &error.into()); Ok(candidate) } CommitOutcome::Retryable(error) => { @@ -199,13 +226,11 @@ async fn commit_recoverable_refresh( } CommitOutcome::RetryCleanupFailed(error) => { let error = anyhow::Error::from(error); - block(&error); - Err(error.context("failed to discard the incomplete profile refresh")) + Err(block(item.name.as_deref(), &error).context("failed to discard the incomplete profile refresh")) } CommitOutcome::NeedsRecovery(error) => { let error = anyhow::Error::from(error); - block(&error); - Err(error.context("profile refresh requires recovery")) + Err(block(item.name.as_deref(), &error)) } } }) @@ -214,8 +239,7 @@ async fn commit_recoverable_refresh( Ok(result) => result, Err(error) => { let error = anyhow::Error::from(error).context("profile storage worker stopped unexpectedly"); - block(&error); - Err(error) + Err(block(None, &error)) } } } @@ -224,6 +248,15 @@ async fn commit_recoverable_refresh( mod tests { use super::*; + #[test] + fn recovery_message_identifies_the_subscription_in_the_active_language() { + let named = RecoveryRequired(Some("工作线路".into())).to_string(); + assert!(named.contains("工作线路")); + let unknown = RecoveryRequired(None).to_string(); + assert!(!unknown.contains("工作线路")); + assert_ne!(unknown, "profileRecovery.unknown"); + } + #[tokio::test] async fn legacy_refresh_reports_a_written_body_when_index_replace_fails() -> Result<()> { let home = tempfile::tempdir()?; diff --git a/src-tauri/src/config/profiles.rs b/src-tauri/src/config/profiles.rs index 5eff68f35..10cc2c528 100644 --- a/src-tauri/src/config/profiles.rs +++ b/src-tauri/src/config/profiles.rs @@ -318,7 +318,11 @@ pub(crate) async fn save_remote_refresh( let _profile_write = PROFILE_WRITE_LOCK.lock().await; anyhow::ensure!(!handle::Handle::global().is_exiting(), "application is exiting"); let draft = Config::profiles().await; - check_refresh_source(draft.data_arc().get_item(&uid)?, &url, file.as_ref())?; + let snapshot = draft.data_arc(); + let source = snapshot.get_item(&uid)?; + check_refresh_source(source, &url, file.as_ref())?; + let name = source.name.clone(); + drop(snapshot); let refresh = prepare_remote_refresh(downloaded, options.as_ref()).await?; let mut storage_guard = None; let mut persisted = false; @@ -346,10 +350,7 @@ pub(crate) async fn save_remote_refresh( if let Err(error) = &result && persisted { - profile_storage::block(error); - return Err(anyhow::anyhow!( - "Profile refresh is saved, but its Draft could not be published: {error:#}" - )); + return Err(profile_storage::block(name.as_deref(), error).context("Profile refresh was saved")); } drop(storage_guard); result?; diff --git a/src/components/profile/profile-item.tsx b/src/components/profile/profile-item.tsx index d8dfeb0a6..4fcd45e82 100644 --- a/src/components/profile/profile-item.tsx +++ b/src/components/profile/profile-item.tsx @@ -41,7 +41,7 @@ import { viewProfile, } from '@/services/cmds' import { mutate } from '@/services/mutate' -import { showNotice } from '@/services/notice-service' +import { failureCode, showNotice } from '@/services/notice-service' import { useProfileLoadingCache, useSetProfileLoading, @@ -431,7 +431,10 @@ const ProfileItemBase = (props: ProfileItemProps) => { }) void mutateProfiles() - } catch { + } catch (err) { + if (failureCode(err) === 'PROFILE_RECOVERY_REQUIRED') { + showNotice.error(err) + } } finally { setLoading(false) } diff --git a/src/pages/profiles.tsx b/src/pages/profiles.tsx index 3f032ae50..f9534e6f7 100644 --- a/src/pages/profiles.tsx +++ b/src/pages/profiles.tsx @@ -16,7 +16,15 @@ import { RefreshRounded, TextSnippetOutlined, } from '@mui/icons-material' -import { Box, Button, Divider, Grid, IconButton, Stack } from '@mui/material' +import { + Alert, + Box, + Button, + Divider, + Grid, + IconButton, + Stack, +} from '@mui/material' import { getCurrentWindow } from '@tauri-apps/api/window' import { readText } from '@tauri-apps/plugin-clipboard-manager' import { readTextFile } from '@tauri-apps/plugin-fs' @@ -50,7 +58,7 @@ import { updateProfile, } from '@/services/cmds' import { mutate } from '@/services/mutate' -import { errorDetail, showNotice } from '@/services/notice-service' +import { errorDetail, failureCode, showNotice } from '@/services/notice-service' import { revalidateQuery, useQuery } from '@/services/query-client' import { useThemeMode } from '@/services/states' import { @@ -553,7 +561,10 @@ const ProfilePage = () => { errorNotice: false, }) throttleMutate() - } catch (err: any) { + } catch (err) { + if (failureCode(err) === 'PROFILE_RECOVERY_REQUIRED') { + showNotice.error(err) + } console.error(`更新订阅 ${uid} 失败:`, err) } } @@ -831,6 +842,9 @@ const ProfilePage = () => { } > + {failureCode(error) === 'PROFILE_RECOVERY_REQUIRED' && ( + {errorDetail(error)} + )}