mirror of
https://github.com/clash-verge-rev/clash-verge-rev.git
synced 2026-11-05 07:02:09 +08:00
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.
This commit is contained in:
@@ -0,0 +1,145 @@
|
||||
// @vitest-environment jsdom
|
||||
import {
|
||||
cleanup,
|
||||
fireEvent,
|
||||
render,
|
||||
screen,
|
||||
waitFor,
|
||||
} from '@testing-library/react'
|
||||
import { afterEach, expect, it, vi } from 'vitest'
|
||||
|
||||
import { getSnapshotNotices, hideNotice } from '@/services/notice-service'
|
||||
import {
|
||||
clearServiceRequest,
|
||||
getServiceRequest,
|
||||
} from '@/services/service-request'
|
||||
|
||||
import ProxyControlSwitches from './proxy-control-switches'
|
||||
|
||||
const patchVerge = vi.hoisted(() => vi.fn(() => Promise.resolve()))
|
||||
const mutateVerge = vi.hoisted(() => vi.fn())
|
||||
const isTunModeAvailable = vi.hoisted(() => ({ current: false }))
|
||||
const tunEnabled = vi.hoisted(() => ({ current: false }))
|
||||
|
||||
vi.mock('react-i18next', () => ({
|
||||
useTranslation: () => ({ t: (key: string) => key }),
|
||||
}))
|
||||
vi.mock('@/hooks/use-verge', () => ({
|
||||
useVerge: () => ({
|
||||
verge: { enable_tun_mode: tunEnabled.current },
|
||||
mutateVerge,
|
||||
patchVerge,
|
||||
}),
|
||||
}))
|
||||
vi.mock('@/hooks/use-system-state', () => ({
|
||||
useSystemState: () => ({
|
||||
runState: { serviceUsable: false },
|
||||
isTunModeAvailable: isTunModeAvailable.current,
|
||||
}),
|
||||
}))
|
||||
vi.mock('@/hooks/use-system-proxy-state', () => ({
|
||||
useSystemProxyState: () => ({
|
||||
indicator: false,
|
||||
toggleSystemProxy: vi.fn(),
|
||||
}),
|
||||
}))
|
||||
vi.mock('@/hooks/use-service-uninstaller', () => ({
|
||||
useServiceUninstaller: () => ({ uninstallServiceAndStartSidecar: vi.fn() }),
|
||||
}))
|
||||
vi.mock('@/components/setting/mods/sysproxy-viewer', () => ({
|
||||
SysproxyViewer: () => null,
|
||||
}))
|
||||
vi.mock('@/components/setting/mods/tun-viewer', () => ({
|
||||
TunViewer: () => null,
|
||||
}))
|
||||
|
||||
afterEach(() => {
|
||||
patchVerge.mockClear()
|
||||
mutateVerge.mockClear()
|
||||
isTunModeAvailable.current = false
|
||||
tunEnabled.current = false
|
||||
clearServiceRequest()
|
||||
getSnapshotNotices().forEach((notice) => hideNotice(notice.id))
|
||||
cleanup()
|
||||
})
|
||||
|
||||
const renderTun = () =>
|
||||
render(
|
||||
<ProxyControlSwitches label="settings.sections.system.toggles.tunMode" />,
|
||||
)
|
||||
|
||||
const theSwitch = () => screen.getByRole('switch') as HTMLInputElement
|
||||
const flip = () => fireEvent.click(theSwitch())
|
||||
|
||||
it('asks for the service when TUN cannot work, saying what it was for', async () => {
|
||||
renderTun()
|
||||
|
||||
flip()
|
||||
|
||||
await waitFor(() =>
|
||||
expect(getServiceRequest()).toEqual({
|
||||
reason: 'tunNeedsService',
|
||||
restore: { enable_tun_mode: true },
|
||||
}),
|
||||
)
|
||||
expect(patchVerge).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('leaves the switch where it was until something can carry the request', async () => {
|
||||
renderTun()
|
||||
|
||||
flip()
|
||||
|
||||
await waitFor(() => expect(theSwitch().checked).toBe(false))
|
||||
})
|
||||
|
||||
it('patches directly when the service can already carry it', async () => {
|
||||
isTunModeAvailable.current = true
|
||||
renderTun()
|
||||
|
||||
flip()
|
||||
|
||||
await waitFor(() =>
|
||||
expect(patchVerge).toHaveBeenCalledWith({ enable_tun_mode: true }),
|
||||
)
|
||||
expect(getServiceRequest()).toBeNull()
|
||||
})
|
||||
|
||||
it('no longer offers a separate install button', () => {
|
||||
renderTun()
|
||||
|
||||
expect(
|
||||
screen.queryByLabelText(
|
||||
'settings.sections.proxyControl.actions.installService',
|
||||
),
|
||||
).toBeNull()
|
||||
})
|
||||
|
||||
it('does not ask for a service in order to turn TUN off', async () => {
|
||||
tunEnabled.current = true
|
||||
renderTun()
|
||||
|
||||
flip()
|
||||
|
||||
await waitFor(() =>
|
||||
expect(patchVerge).toHaveBeenCalledWith({ enable_tun_mode: false }),
|
||||
)
|
||||
expect(getServiceRequest()).toBeNull()
|
||||
})
|
||||
|
||||
it('says nothing beside the dialog it just opened', async () => {
|
||||
const onError = vi.fn()
|
||||
render(
|
||||
<ProxyControlSwitches
|
||||
label="settings.sections.system.toggles.tunMode"
|
||||
onError={onError}
|
||||
/>,
|
||||
)
|
||||
|
||||
flip()
|
||||
|
||||
await waitFor(() => expect(getServiceRequest()).not.toBeNull())
|
||||
await waitFor(() => expect(theSwitch().checked).toBe(false))
|
||||
expect(onError).not.toHaveBeenCalled()
|
||||
expect(getSnapshotNotices()).toEqual([])
|
||||
})
|
||||
@@ -1,5 +1,4 @@
|
||||
import {
|
||||
BuildRounded,
|
||||
DeleteForeverRounded,
|
||||
PauseCircleOutlineRounded,
|
||||
PlayCircleOutlineRounded,
|
||||
@@ -8,18 +7,18 @@ import {
|
||||
} from '@mui/icons-material'
|
||||
import { Box, Typography, alpha, useTheme } from '@mui/material'
|
||||
import { useLockFn } from 'ahooks'
|
||||
import React, { useCallback, useRef, useState } from 'react'
|
||||
import React, { useRef, useState } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
|
||||
import { DialogRef, Switch, TooltipIcon } from '@/components/base'
|
||||
import { SysproxyViewer } from '@/components/setting/mods/sysproxy-viewer'
|
||||
import { TunViewer } from '@/components/setting/mods/tun-viewer'
|
||||
import { useServiceInstaller } from '@/hooks/use-service-installer'
|
||||
import { useServiceUninstaller } from '@/hooks/use-service-uninstaller'
|
||||
import { useSystemProxyState } from '@/hooks/use-system-proxy-state'
|
||||
import { useSystemState } from '@/hooks/use-system-state'
|
||||
import { useVerge } from '@/hooks/use-verge'
|
||||
import { showNotice } from '@/services/notice-service'
|
||||
import { requestService } from '@/services/service-request'
|
||||
|
||||
interface ProxySwitchProps {
|
||||
label?: string
|
||||
@@ -34,7 +33,8 @@ interface SwitchRowProps {
|
||||
infoTitle: string
|
||||
onInfoClick?: () => void
|
||||
extraIcons?: React.ReactNode
|
||||
onToggle: (value: boolean) => Promise<void>
|
||||
/** Return false to roll back without reporting an error. */
|
||||
onToggle: (value: boolean) => Promise<boolean | void>
|
||||
onError?: (err: Error) => void
|
||||
highlight?: boolean
|
||||
}
|
||||
@@ -68,6 +68,9 @@ const SwitchRow = ({
|
||||
pendingRef.current = true
|
||||
setChecked(value)
|
||||
onToggle(value)
|
||||
.then((applied) => {
|
||||
if (applied === false) setChecked(active)
|
||||
})
|
||||
.catch((err: any) => {
|
||||
setChecked(active)
|
||||
onError?.(err)
|
||||
@@ -131,11 +134,10 @@ const ProxyControlSwitches = ({
|
||||
}: ProxySwitchProps) => {
|
||||
const { t } = useTranslation()
|
||||
const { verge, mutateVerge, patchVerge } = useVerge()
|
||||
const { installServiceAndRestartCore } = useServiceInstaller()
|
||||
const { uninstallServiceAndStartSidecar } = useServiceUninstaller()
|
||||
const { indicator: systemProxyIndicator, toggleSystemProxy } =
|
||||
useSystemProxyState()
|
||||
const { runState, isTunModeAvailable, mutateSystemState } = useSystemState()
|
||||
const { runState, isTunModeAvailable } = useSystemState()
|
||||
// Offer to uninstall only a service that is actually there and working.
|
||||
const isServiceInstallReady = runState.serviceUsable
|
||||
|
||||
@@ -144,30 +146,18 @@ const ProxyControlSwitches = ({
|
||||
|
||||
const { enable_tun_mode } = verge ?? {}
|
||||
|
||||
const showErrorNotice = useCallback(
|
||||
(msg: string) => showNotice.error(msg),
|
||||
[],
|
||||
)
|
||||
|
||||
const handleTunToggle = async (value: boolean) => {
|
||||
if (!isTunModeAvailable) {
|
||||
const msgKey = 'settings.sections.proxyControl.tooltips.tunUnavailable'
|
||||
showErrorNotice(msgKey)
|
||||
throw new Error(t(msgKey))
|
||||
if (value && !isTunModeAvailable) {
|
||||
requestService({
|
||||
reason: 'tunNeedsService',
|
||||
restore: { enable_tun_mode: value },
|
||||
})
|
||||
return false
|
||||
}
|
||||
mutateVerge({ ...verge, enable_tun_mode: value }, false)
|
||||
await patchVerge({ enable_tun_mode: value })
|
||||
}
|
||||
|
||||
const onInstallService = useLockFn(async () => {
|
||||
try {
|
||||
await installServiceAndRestartCore()
|
||||
await mutateSystemState()
|
||||
} catch (err) {
|
||||
showNotice.error(err)
|
||||
}
|
||||
})
|
||||
|
||||
const onUninstallService = useLockFn(async () => {
|
||||
try {
|
||||
await uninstallServiceAndStartSidecar()
|
||||
@@ -202,29 +192,17 @@ const ProxyControlSwitches = ({
|
||||
onInfoClick={() => tunRef.current?.open()}
|
||||
onToggle={handleTunToggle}
|
||||
onError={onError}
|
||||
disabled={!isTunModeAvailable}
|
||||
highlight={enable_tun_mode || false}
|
||||
extraIcons={
|
||||
<>
|
||||
{!isTunModeAvailable && (
|
||||
<>
|
||||
<TooltipIcon
|
||||
title={t(
|
||||
'settings.sections.proxyControl.tooltips.tunUnavailable',
|
||||
)}
|
||||
icon={WarningRounded}
|
||||
sx={{ color: 'warning.main', ml: 1 }}
|
||||
/>
|
||||
<TooltipIcon
|
||||
title={t(
|
||||
'settings.sections.proxyControl.actions.installService',
|
||||
)}
|
||||
icon={BuildRounded}
|
||||
color="primary"
|
||||
onClick={onInstallService}
|
||||
sx={{ ml: 1 }}
|
||||
/>
|
||||
</>
|
||||
<TooltipIcon
|
||||
title={t(
|
||||
'settings.sections.proxyControl.tooltips.tunUnavailable',
|
||||
)}
|
||||
icon={WarningRounded}
|
||||
sx={{ color: 'warning.main', ml: 1 }}
|
||||
/>
|
||||
)}
|
||||
{isServiceInstallReady && (
|
||||
<TooltipIcon
|
||||
|
||||
Reference in New Issue
Block a user