Files
clash-verge-rev/src/components/setting/mods/backup-config-viewer.tsx
T
wonfen 22947632c0 refactor: Rewrite and improve sysproxy logic (#7744)
* fix(cmd): preserve anyhow context in coded errors

Use alternate error formatting so coded failures retain the full anyhow context chain without changing their wire format.

* fix(macos): skip redundant proxy disable writes

When both proxy modes are off, read macOS state first and skip networksetup if the OS is already clean. Update the guard target only after a successful write.

* feat(proxy): classify system proxy failures

Attach stable, actionable proxy failure codes to anyhow chains while preserving the original diagnostic causes.

* feat(cmd): return structured command failures

Replace encoded error strings with serializable code and detail fields, and update frontend notice consumers to handle the structured shape.

* fix(scripts): use the js-yaml namespace import

Import js-yaml through its ESM namespace so the i18n cleanup script can access load and dump.

* feat(proxy): localize classified proxy failures

Map privilege and direct-fallback codes to localized explanations, and let mapped causes outrank generic operation keys in notices.

* fix(ui): bound notice text and render failure details

Limit resolved notice text without truncating clipboard content, and normalize structured failures embedded in translation parameters.

* feat(proxy): persist unseen proxy failures

Store unresolved classified failures by code, notify the frontend when the table changes, and show each failure sequence once when a visible window can receive it.

* feat(proxy): report tray and hotkey toggle failures

Record classified failures from tray and hotkey proxy toggles so they appear when a visible window is available.

* fix(ui): restore the proxy switch after failed toggles

Refresh frontend proxy state after a failed toggle so the switch reflects the rolled-back configuration.

* feat(proxy): stop the guard after repeated failures

Report guard outcomes, stop after the failure threshold, and persist the classified failure for the frontend.

* fix(macos): preserve proxy during service handoff

Stop a sidecar being handed to the service without clearing proxy state that the new owner must inherit.

* feat(macos): classify misplaced sidecar state

Distinguish a refused sidecar proxy write from a machine that still needs the privileged service installed.

* feat(ui): recover misplaced sidecar notices

Offer a restart action for macOS proxy failures caused by a ready service while the core still runs as a sidecar.

* feat(ui): install the service from proxy notices

Let privilege notices install the macOS service, restart the core, and report the runtime mode that was actually reached.

* feat(cmd): attach requested proxy operations

Carry the requested proxy direction with structured command failures when the originating command knows it.

* feat(sysproxy): drain guards before OS access

Wait for the local proxy guard to stop before OS reads, service handoff, or final writes, and refuse transitions when it does not drain.

* feat(sysproxy): recover partial proxy writes

Use write progress to choose whether to restore the old guard or compensate with a disabled proxy state, while preserving actionable errors.

* feat(sysproxy): skip already-applied proxy writes

Compare macOS proxy snapshots with global, PAC, and disabled targets so matching state avoids redundant privileged writes.

* feat(proxy): report background proxy failures

Persist and surface classified proxy failures from lifecycle paths that have no direct caller awaiting the result.

* feat(ui): move proxy recovery into a dialog

Guide users through installing or switching to the service after a refused proxy write, and suppress duplicate toast reports.

* fix(ui): close proxy dialog after service recovery

Dismiss the recovery dialog once the core reaches service mode, even when the original proxy request remains pending.

* feat(ui): retry proxy request after service recovery

Replay the requested proxy direction after the core reaches service mode, while leaving incidental restores unchanged.

* fix(proxy): refresh state after successful apply

Publish the proxy refresh from the shared apply path after releasing the lifecycle lock, and remove the tray-specific duplicate.

* feat(ui): show proxy recovery progress

Display installation, restart, and proxy-apply stages while keeping the primary action spinner visible during recovery.

* feat(ui): route unavailable TUN through service recovery

Let the TUN switch request service recovery and restore its requested state after the core restarts in service mode.

* fix(ui): avoid duplicate TUN recovery errors

Roll back deferred TUN toggles without reporting an error, and publish configuration refreshes from the transaction commit path.

* chore: update changelog & pinlock

* fix(core): resolve platform-specific clippy warnings

* fix(core): detect Windows wildcard TCP conflicts

Windows permits a specific exclusive bind beside an existing non-exclusive wildcard listener. Consult the system TCP listener table so the probe reports that overlap as a conflict.
2026-08-14 23:52:37 +08:00

284 lines
8.9 KiB
TypeScript

import Visibility from '@mui/icons-material/Visibility'
import VisibilityOff from '@mui/icons-material/VisibilityOff'
import {
TextField,
Button,
Grid,
Stack,
IconButton,
InputAdornment,
} from '@mui/material'
import { useLockFn } from 'ahooks'
import { useState, useRef, memo, useEffect } from 'react'
import { useForm } from 'react-hook-form'
import { useTranslation } from 'react-i18next'
import { useVerge } from '@/hooks/use-verge'
import { saveWebdavConfig, createWebdavBackup } from '@/services/cmds'
import { errorDetail, showNotice } from '@/services/notice-service'
import {
buildWebdavSignature,
getWebdavStatus,
setWebdavStatus,
} from '@/services/webdav-status'
import { isValidUrl } from '@/utils/network'
interface BackupConfigViewerProps {
onBackupSuccess: () => Promise<void>
onSaveSuccess: (signature?: string) => Promise<void>
onRefresh: () => Promise<void>
onInit: () => Promise<void>
setLoading: (loading: boolean) => void
}
export const BackupConfigViewer = memo(
({
onBackupSuccess,
onSaveSuccess,
onRefresh,
onInit,
setLoading,
}: BackupConfigViewerProps) => {
const { t } = useTranslation()
const { verge, mutateVerge } = useVerge()
const { webdav_url, webdav_username, webdav_password } = verge || {}
const [showPassword, setShowPassword] = useState(false)
const usernameRef = useRef<HTMLInputElement>(null)
const passwordRef = useRef<HTMLInputElement>(null)
const urlRef = useRef<HTMLInputElement>(null)
const { register, handleSubmit, watch } = useForm<IWebDavConfig>({
defaultValues: {
url: webdav_url,
username: webdav_username,
password: webdav_password,
},
})
const url = watch('url')
const username = watch('username')
const password = watch('password')
const webdavChanged =
webdav_url !== url ||
webdav_username !== username ||
webdav_password !== password
const webdavSignature = buildWebdavSignature(verge)
const webdavStatus = getWebdavStatus(webdavSignature)
const shouldAutoInit = webdavStatus !== 'failed'
const handleClickShowPassword = () => {
setShowPassword((prev) => !prev)
}
useEffect(() => {
if (!webdav_url || !webdav_username || !webdav_password) {
return
}
if (!shouldAutoInit) {
return
}
void onInit()
}, [webdav_url, webdav_username, webdav_password, onInit, shouldAutoInit])
const checkForm = () => {
const username = usernameRef.current?.value
const password = passwordRef.current?.value
const url = urlRef.current?.value
if (!url) {
urlRef.current?.focus()
showNotice.error('settings.modals.backup.messages.webdavUrlRequired')
throw new Error(t('settings.modals.backup.messages.webdavUrlRequired'))
} else if (!isValidUrl(url)) {
urlRef.current?.focus()
showNotice.error('settings.modals.backup.messages.invalidWebdavUrl')
throw new Error(t('settings.modals.backup.messages.invalidWebdavUrl'))
}
if (!username) {
usernameRef.current?.focus()
showNotice.error('settings.modals.backup.messages.usernameRequired')
throw new Error(t('settings.modals.backup.messages.usernameRequired'))
}
if (!password) {
passwordRef.current?.focus()
showNotice.error('settings.modals.backup.messages.passwordRequired')
throw new Error(t('settings.modals.backup.messages.passwordRequired'))
}
}
const save = useLockFn(async (data: IWebDavConfig) => {
checkForm()
const signature = buildWebdavSignature({
webdav_url: data.url,
webdav_username: data.username,
webdav_password: data.password,
})
const trimmedUrl = data.url.trim()
const trimmedUsername = data.username.trim()
try {
setLoading(true)
await saveWebdavConfig(trimmedUrl, trimmedUsername, data.password)
await mutateVerge(
(current) =>
current
? {
...current,
webdav_url: trimmedUrl,
webdav_username: trimmedUsername,
webdav_password: data.password,
}
: current,
false,
)
setWebdavStatus(signature, 'unknown')
showNotice.success('settings.modals.backup.messages.webdavConfigSaved')
await onSaveSuccess(signature)
} catch (error) {
showNotice.error(
'settings.modals.backup.messages.webdavConfigSaveFailed',
{ error: errorDetail(error) },
3000,
)
} finally {
setLoading(false)
}
})
const handleBackup = useLockFn(async () => {
checkForm()
const signature = buildWebdavSignature({
webdav_url: url,
webdav_username: username,
webdav_password: password,
})
try {
setLoading(true)
await createWebdavBackup().then(async () => {
showNotice.success('settings.modals.backup.messages.backupCreated')
await onBackupSuccess()
})
setWebdavStatus(signature, 'ready')
} catch (error) {
showNotice.error('settings.modals.backup.messages.backupFailed', {
error,
})
setWebdavStatus(signature, 'failed')
} finally {
setLoading(false)
}
})
return (
<form onSubmit={(e) => e.preventDefault()}>
<Grid container spacing={2}>
<Grid size={{ xs: 12, sm: 9 }}>
<Grid container spacing={2}>
<Grid size={{ xs: 12 }}>
<TextField
fullWidth
label={t('settings.modals.backup.fields.webdavUrl')}
variant="outlined"
size="small"
{...register('url')}
autoCorrect="off"
autoCapitalize="off"
spellCheck="false"
inputRef={urlRef}
sx={{ mt: 1 }}
/>
</Grid>
<Grid size={{ xs: 6 }}>
<TextField
label={t('settings.modals.backup.fields.username')}
variant="outlined"
size="small"
{...register('username')}
autoCorrect="off"
autoCapitalize="off"
spellCheck="false"
inputRef={usernameRef}
/>
</Grid>
<Grid size={{ xs: 6 }}>
<TextField
label={t('shared.labels.password')}
type={showPassword ? 'text' : 'password'}
variant="outlined"
size="small"
autoCorrect="off"
autoCapitalize="off"
spellCheck="false"
inputRef={passwordRef}
{...register('password')}
slotProps={{
input: {
endAdornment: (
<InputAdornment position="end">
<IconButton
onClick={handleClickShowPassword}
edge="end"
>
{showPassword ? <VisibilityOff /> : <Visibility />}
</IconButton>
</InputAdornment>
),
},
}}
/>
</Grid>
</Grid>
</Grid>
<Grid size={{ xs: 12, sm: 3 }}>
<Stack
direction="column"
sx={{
justifyContent: 'space-between',
alignItems: 'stretch',
height: '100%',
}}
>
{webdavChanged ||
webdav_url === undefined ||
webdav_username === undefined ||
webdav_password === undefined ? (
<Button
variant="contained"
color={'primary'}
sx={{ height: '100%' }}
type="button"
onClick={handleSubmit(save)}
>
{t('shared.actions.save')}
</Button>
) : (
<>
<Button
variant="contained"
color="success"
onClick={handleBackup}
type="button"
size="large"
>
{t('settings.modals.backup.actions.backup')}
</Button>
<Button
variant="outlined"
onClick={onRefresh}
type="button"
size="large"
>
{t('shared.actions.refresh')}
</Button>
</>
)}
</Stack>
</Grid>
</Grid>
</form>
)
},
)