fix(profile): report manual refresh failures once

This commit is contained in:
Tunglies
2026-12-04 12:31:34 +08:00
parent 333ffe5f64
commit 20b7a4a0e7
25 changed files with 74 additions and 122 deletions
+1
View File
@@ -28,6 +28,7 @@
<details>
<summary><strong> 🐞 修复问题 </strong></summary>
- 修复手动更新订阅时错误提示缺失或重复,显示订阅名称和失败原因
- 优化订阅恢复失败提示,显示受影响的订阅名称
- 修复「外部控制器」复制成功的提示一闪而过
- 修复订阅的规则、代理组、节点编辑器快速连续操作时条目可能重复或错位
+1 -5
View File
@@ -36,8 +36,6 @@ pub enum NoticeStatus {
AppQuitCoreStopFailed,
#[serde(rename = "update_with_clash_proxy")]
UpdateWithClashProxy,
#[serde(rename = "update_failed_even_with_clash")]
UpdateFailedEvenWithClash,
#[serde(rename = "reactivate_profiles::error")]
ReactivateProfilesError,
#[serde(rename = "update_failed")]
@@ -81,7 +79,7 @@ impl NoticeStatus {
/// test both derive their variant list from here; expected strings stay
/// hand-written in the test so renames cannot slip through.
#[cfg(test)]
pub const ALL: [Self; 33] = [
pub const ALL: [Self; 32] = [
Self::ImportSubUrlOk,
Self::ImportSubUrlError,
Self::SetConfigError,
@@ -96,7 +94,6 @@ impl NoticeStatus {
Self::AppRestartCoreStopFailed,
Self::AppQuitCoreStopFailed,
Self::UpdateWithClashProxy,
Self::UpdateFailedEvenWithClash,
Self::ReactivateProfilesError,
Self::UpdateFailed,
Self::ConfigValidateBootError,
@@ -140,7 +137,6 @@ mod tests {
"app_restart::core_stop_failed",
"app_quit::core_stop_failed",
"update_with_clash_proxy",
"update_failed_even_with_clash",
"reactivate_profiles::error",
"update_failed",
"config_validate::boot_error",
+11 -27
View File
@@ -50,12 +50,7 @@ async fn refresh_source(uid: &str, ignore_auto_update: bool) -> Result<Option<Re
}
#[tracing::instrument(skip_all, level = "info", fields(uid = %uid, strategy = tracing::field::Empty, configured_elapsed = tracing::field::Empty, clash_elapsed = tracing::field::Empty, system_elapsed = tracing::field::Empty))]
async fn perform_profile_update(
uid: &str,
source: RefreshSource,
overrides: Option<&PrfOption>,
is_manual_trigger: bool,
) -> Result<()> {
async fn perform_profile_update(uid: &str, source: RefreshSource, overrides: Option<&PrfOption>) -> Result<()> {
let url = source.url.as_str();
let options = PrfOption::merge(source.option.as_ref(), overrides);
let download_options = options.as_ref();
@@ -113,26 +108,13 @@ async fn perform_profile_update(
},
)
.await;
let last_err = match result {
Ok((strategy, downloaded)) => {
// A persistence error must not replay a successful download with another transport.
save_remote_refresh(uid, source.url, source.file, downloaded, options).await?;
if !matches!(strategy, Strategy::Configured) {
handle::Handle::notice(NoticeStatus::UpdateWithClashProxy, profile_name);
}
return Ok(());
}
Err(error) => error,
};
let last_err = mask_err(&last_err.to_string());
if is_manual_trigger {
handle::Handle::notice(
NoticeStatus::UpdateFailedEvenWithClash,
format!("{profile_name} - {last_err}"),
);
let (strategy, downloaded) = result.map_err(|err| anyhow::anyhow!(mask_err(&format!("{err:#}"))))?;
// A persistence error must not replay a successful download with another transport.
save_remote_refresh(uid, source.url, source.file, downloaded, options).await?;
if !matches!(strategy, Strategy::Configured) {
handle::Handle::notice(NoticeStatus::UpdateWithClashProxy, profile_name);
}
bail!(last_err)
Ok(())
}
#[tracing::instrument(skip_all, level = "info", fields(uid = %uid, manual = is_manual_trigger))]
@@ -141,7 +123,7 @@ pub async fn update_profile(uid: &str, option: Option<&PrfOption>, is_manual_tri
let profile_persisted = match subscription {
Some(source) => {
perform_profile_update(uid, source, option, is_manual_trigger).await?;
perform_profile_update(uid, source, option).await?;
true
}
None => false,
@@ -169,7 +151,9 @@ pub async fn update_profile(uid: &str, option: Option<&PrfOption>, is_manual_tri
message
};
logging!(error, Type::Config, "[订阅更新] 更新失败: {}", message);
handle::Handle::notice(NoticeStatus::UpdateFailed, message.as_str());
if !is_manual_trigger {
handle::Handle::notice(NoticeStatus::UpdateFailed, message.as_str());
}
bail!(message);
}
}
+1 -10
View File
@@ -26,7 +26,6 @@ import { useNavigate } from 'react-router'
import { useAppRefreshers } from '@/providers/app-data-context'
import { updateProfile } from '@/services/cmds'
import { mutate } from '@/services/mutate'
import { showNotice } from '@/services/notice-service'
import { isValidUrl } from '@/utils/network'
import { openExternalUrl } from '@/utils/open-external-url'
@@ -279,19 +278,11 @@ export const HomeProfileCard = ({
setUpdating(true)
try {
await mutate(
() => updateProfile(current.uid!, current.option ?? undefined),
{
id: `update-profile:${current.uid}`,
errorNotice: false,
},
)
if (!(await updateProfile(current, current.option ?? undefined))) return
onProfileUpdated?.()
// 刷新首页数据
refreshAll()
} catch (err) {
showNotice.error(err, 3000)
} finally {
setUpdating(false)
}
+2 -11
View File
@@ -41,7 +41,7 @@ import {
viewProfile,
} from '@/services/cmds'
import { mutate } from '@/services/mutate'
import { failureCode, showNotice } from '@/services/notice-service'
import { showNotice } from '@/services/notice-service'
import {
useProfileLoadingCache,
useSetProfileLoading,
@@ -425,16 +425,7 @@ const ProfileItemBase = (props: ProfileItemProps) => {
try {
const payload = Object.keys(option).length > 0 ? option : undefined
await mutate(() => updateProfile(itemData.uid!, payload), {
id: `update-profile:${itemData.uid}`,
errorNotice: false,
})
void mutateProfiles()
} catch (err) {
if (failureCode(err) === 'PROFILE_RECOVERY_REQUIRED') {
showNotice.error(err)
}
if (await updateProfile(itemData, payload)) void mutateProfiles()
} finally {
setLoading(false)
}
+1 -2
View File
@@ -701,8 +701,7 @@
"uninstallSuccess": "تم إلغاء تثبيت الخدمة بنجاح"
},
"updater": {
"withClashProxySuccess": "Update with Clash proxy successfully",
"withClashProxyFailed": "Update failed even with Clash proxy"
"withClashProxySuccess": "Update with Clash proxy successfully"
}
}
},
+1 -2
View File
@@ -701,8 +701,7 @@
"uninstallSuccess": "Service erfolgreich deinstalliert"
},
"updater": {
"withClashProxySuccess": "Aktualisierung mit Clash-Proxy erfolgreich",
"withClashProxyFailed": "Aktualisierung auch mit Clash-Proxy fehlgeschlagen"
"withClashProxySuccess": "Aktualisierung mit Clash-Proxy erfolgreich"
}
}
},
+1 -2
View File
@@ -701,8 +701,7 @@
"uninstallSuccess": "Service Uninstalled Successfully"
},
"updater": {
"withClashProxySuccess": "Update with Clash proxy successfully",
"withClashProxyFailed": "Update failed even with Clash proxy"
"withClashProxySuccess": "Update with Clash proxy successfully"
}
}
},
+1 -2
View File
@@ -701,8 +701,7 @@
"uninstallSuccess": "Servicio desinstalado con éxito"
},
"updater": {
"withClashProxySuccess": "Actualización con el proxy de Clash exitosa",
"withClashProxyFailed": "Error al actualizar incluso con el proxy de Clash"
"withClashProxySuccess": "Actualización con el proxy de Clash exitosa"
}
}
},
+1 -2
View File
@@ -701,8 +701,7 @@
"uninstallSuccess": "سرویس با موفقیت حذف نصب شد"
},
"updater": {
"withClashProxySuccess": "با موفقیت با پروکسی کلش به‌روزرسانی شد",
"withClashProxyFailed": "به‌روزرسانی حتی با پروکسی کلش هم انجام نشد"
"withClashProxySuccess": "با موفقیت با پروکسی کلش به‌روزرسانی شد"
}
}
},
+1 -2
View File
@@ -701,8 +701,7 @@
"uninstallSuccess": "Layanan Berhasil Dicopot"
},
"updater": {
"withClashProxySuccess": "Update with Clash proxy successfully",
"withClashProxyFailed": "Update failed even with Clash proxy"
"withClashProxySuccess": "Update with Clash proxy successfully"
}
}
},
+1 -2
View File
@@ -701,8 +701,7 @@
"uninstallSuccess": "サービスのアンインストールに成功しました。"
},
"updater": {
"withClashProxySuccess": "Clashプロキシを使用して更新に成功しました。",
"withClashProxyFailed": "Clashプロキシを使用しても更新に失敗しました。"
"withClashProxySuccess": "Clashプロキシを使用して更新に成功しました。"
}
}
},
+1 -2
View File
@@ -701,8 +701,7 @@
"uninstallSuccess": "서비스가 제거되었습니다"
},
"updater": {
"withClashProxySuccess": "Clash 프록시로 업데이트 성공",
"withClashProxyFailed": "Clash 프록시로도 업데이트 실패"
"withClashProxySuccess": "Clash 프록시로 업데이트 성공"
}
}
},
+1 -2
View File
@@ -701,8 +701,7 @@
"uninstallSuccess": "Serviço Desinstalado com Sucesso"
},
"updater": {
"withClashProxySuccess": "Atualização com o proxy do Clash concluída com sucesso",
"withClashProxyFailed": "A atualização falhou mesmo com o proxy do Clash"
"withClashProxySuccess": "Atualização com o proxy do Clash concluída com sucesso"
}
}
},
+1 -2
View File
@@ -701,8 +701,7 @@
"uninstallSuccess": "Служба успешно удалена"
},
"updater": {
"withClashProxySuccess": "Обновление через Clash proxy выполнено успешно",
"withClashProxyFailed": "Обновление не удалось даже через Clash proxy"
"withClashProxySuccess": "Обновление через Clash proxy выполнено успешно"
}
}
},
+1 -2
View File
@@ -701,8 +701,7 @@
"uninstallSuccess": "Hizmet Başarıyla Kaldırıldı"
},
"updater": {
"withClashProxySuccess": "Clash vekil ile güncelleme başarılı",
"withClashProxyFailed": "Clash vekil ile bile güncelleme başarısız oldu"
"withClashProxySuccess": "Clash vekil ile güncelleme başarılı"
}
}
},
+1 -2
View File
@@ -701,8 +701,7 @@
"uninstallSuccess": "Сервис уңышлы салдырылды"
},
"updater": {
"withClashProxySuccess": "Update with Clash proxy successfully",
"withClashProxyFailed": "Update failed even with Clash proxy"
"withClashProxySuccess": "Update with Clash proxy successfully"
}
}
},
+1 -2
View File
@@ -701,8 +701,7 @@
"uninstallSuccess": "已成功卸载服务"
},
"updater": {
"withClashProxySuccess": "使用 Clash 代理更新成功",
"withClashProxyFailed": "使用 Clash 代理更新失败"
"withClashProxySuccess": "使用 Clash 代理更新成功"
}
}
},
+1 -2
View File
@@ -701,8 +701,7 @@
"uninstallSuccess": "已成功解除安裝服務"
},
"updater": {
"withClashProxySuccess": "使用 Clash 代理更新成功",
"withClashProxyFailed": "使用 Clash 代理更新也失敗"
"withClashProxySuccess": "使用 Clash 代理更新成功"
}
}
},
+18 -30
View File
@@ -545,55 +545,43 @@ const ProfilePage = () => {
const setLoadingProfiles = useSetProfileLoading()
const runProfileUpdates = useCallback(
async (uids: string[]) => {
if (uids.length === 0) return
async (items: IProfileItem[]) => {
if (items.length === 0) return
const throttleMutate = throttle(mutateProfiles, 2000, {
trailing: true,
})
let cursor = 0
const updateOne = async (uid: string) => {
try {
// Per-uid id: the worker pool must not dedupe distinct subscriptions.
await mutate(() => updateProfile(uid), {
id: `update-profile:${uid}`,
errorNotice: false,
})
throttleMutate()
} catch (err) {
if (failureCode(err) === 'PROFILE_RECOVERY_REQUIRED') {
showNotice.error(err)
}
console.error(`更新订阅 ${uid} 失败:`, err)
}
}
const worker = async () => {
while (cursor < uids.length) {
const uid = uids[cursor++]
await updateOne(uid)
while (cursor < items.length) {
if (await updateProfile(items[cursor++])) throttleMutate()
}
}
try {
const active = Math.min(PROFILE_UPDATE_WORKER_LIMIT, uids.length)
const active = Math.min(PROFILE_UPDATE_WORKER_LIMIT, items.length)
await Promise.allSettled(Array.from({ length: active }, worker))
} finally {
setLoadingProfiles(uids, false)
setLoadingProfiles(
items.map((item) => item.uid!),
false,
)
void mutateProfiles()
}
},
[mutateProfiles, setLoadingProfiles],
)
const onUpdateAll = useLockFn(async () => {
const items = profileItems.filter((e) => e.type === 'remote')
const target = items
.map((item) => item.uid!)
.filter((uid) => !loadingCache.has(uid))
setLoadingProfiles(target, true)
await runProfileUpdates(target)
const items = profileItems.filter(
(item) =>
item.type === 'remote' && item.uid && !loadingCache.has(item.uid),
)
setLoadingProfiles(
items.map((item) => item.uid!),
true,
)
await runProfileUpdates(items)
})
const onCopyLink = async () => {
-1
View File
@@ -635,7 +635,6 @@ export type NoticeStatus =
| 'app_restart::core_stop_failed'
| 'app_quit::core_stop_failed'
| 'update_with_clash_proxy'
| 'update_failed_even_with_clash'
| 'reactivate_profiles::error'
| 'update_failed'
| 'config_validate::boot_error'
+26 -3
View File
@@ -1,7 +1,8 @@
import { Channel } from '@tauri-apps/api/core'
import dayjs from 'dayjs'
import { showNotice } from '@/services/notice-service'
import { mutate } from '@/services/mutate'
import { errorDetail, failureCode, showNotice } from '@/services/notice-service'
import { debugLog } from '@/utils/debug'
import { commands } from './bindings'
@@ -82,8 +83,30 @@ export async function reorderProfile(activeId: string, overId: string) {
return commands.reorderProfile(activeId, overId)
}
export async function updateProfile(index: string, option?: IProfileOption) {
return commands.updateProfile(index, option ?? null)
export async function updateProfile(
item: IProfileItem,
option?: IProfileOption,
) {
if (!item.uid) return false
const uid = item.uid
try {
await mutate(() => commands.updateProfile(uid, option ?? null), {
id: `update-profile:${uid}`,
errorNotice: false,
})
return true
} catch (error) {
if (failureCode(error) === 'PROFILE_RECOVERY_REQUIRED') {
showNotice.error(error)
return false
}
const detail = errorDetail(error)
showNotice.error(
'profiles.page.feedback.errors.updateFailed',
item.name?.trim() ? `${item.name} - ${detail}` : detail,
)
return false
}
}
export async function deleteProfile(index: string) {
-5
View File
@@ -182,11 +182,6 @@ const handlers: Record<
'settings.feedback.notifications.updater.withClashProxySuccess',
msg,
),
update_failed_even_with_clash: (msg) =>
showNotice.error(
'settings.feedback.notifications.updater.withClashProxyFailed',
msg,
),
'reactivate_profiles::error': (msg) => showNotice.error(msg),
update_failed: (msg) => showNotice.error(msg),
'config_validate::boot_error': (msg) =>
-1
View File
@@ -860,7 +860,6 @@ export const translationKeys = [
'settings.feedback.notifications.clashService.sidecarFallback',
'settings.feedback.notifications.clashService.uninstallSuccess',
'settings.feedback.notifications.updater.withClashProxySuccess',
'settings.feedback.notifications.updater.withClashProxyFailed',
'settings.statuses.clash.stopping',
'settings.statuses.clash.restarting',
'settings.statuses.clashService.installing',
-1
View File
@@ -898,7 +898,6 @@ export interface TranslationResources {
uninstallSuccess: string
}
updater: {
withClashProxyFailed: string
withClashProxySuccess: string
}
}