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:
wonfen
2026-08-14 23:52:37 +08:00
committed by GitHub
parent 0844ed30a8
commit 22947632c0
93 changed files with 5208 additions and 337 deletions
+147
View File
@@ -0,0 +1,147 @@
// @vitest-environment jsdom
import { act, cleanup, renderHook } from '@testing-library/react'
import { afterEach, beforeEach, expect, it, vi } from 'vitest'
import { useSystemProxyState } from './use-system-proxy-state'
const patchVergeConfig = vi.hoisted(() => vi.fn())
const mutateVerge = vi.hoisted(() => vi.fn())
const getCacheData = vi.hoisted(() => vi.fn())
const revalidateQueries = vi.hoisted(() => vi.fn())
const CACHED: IVergeConfig = { enable_system_proxy: false } as IVergeConfig
vi.mock('@/hooks/use-verge', () => ({
useVerge: () => ({ verge: CACHED, mutateVerge }),
}))
vi.mock('@/hooks/use-displayed-mixed-port', () => ({
useDisplayedMixedPort: () => 7897,
}))
vi.mock('@/providers/app-data-context', () => ({
useSystemData: () => ({ sysproxy: undefined }),
}))
vi.mock('@/services/cmds', () => ({
getAutotemProxy: vi.fn(),
getEmbeddedServerPort: vi.fn(),
patchVergeConfig,
}))
vi.mock('tauri-plugin-mihomo-api', () => ({
closeAllConnections: vi.fn(() => Promise.resolve()),
}))
vi.mock('@/services/query-client', () => ({
useQuery: () => ({ data: undefined }),
getCacheData,
revalidateQueries,
}))
beforeEach(() => {
patchVergeConfig.mockReset()
mutateVerge.mockReset()
getCacheData.mockReset()
getCacheData.mockReturnValue(CACHED)
revalidateQueries.mockReset()
revalidateQueries.mockResolvedValue([])
})
afterEach(() => {
cleanup()
})
const lastWrite = () => {
const call = mutateVerge.mock.calls[mutateVerge.mock.calls.length - 1]?.[0]
return typeof call === 'function' ? call(CACHED) : call
}
it('puts the cache back when the toggle fails', async () => {
patchVergeConfig.mockRejectedValue({
code: 'SYSPROXY_PRIVILEGE_REQUIRED',
detail: 'refused',
})
const { result } = renderHook(() => useSystemProxyState())
await act(async () => {
await expect(result.current.toggleSystemProxy(true)).rejects.toBeTruthy()
})
expect(lastWrite()).toMatchObject({ enable_system_proxy: false })
})
it('falls back to what the last successful click reached, not to where the run began', async () => {
patchVergeConfig.mockResolvedValueOnce(undefined).mockRejectedValueOnce({
code: 'SYSPROXY_PRIVILEGE_REQUIRED',
detail: 'refused',
})
getCacheData.mockReturnValue({ enable_system_proxy: true } as IVergeConfig)
const { result } = renderHook(() => useSystemProxyState())
await act(async () => {
const inFlight = result.current.toggleSystemProxy(false)
void result.current.toggleSystemProxy(true)
await expect(inFlight).rejects.toBeTruthy()
})
expect(lastWrite()).toMatchObject({ enable_system_proxy: false })
})
it('lets a revalidation failure surface when the toggle itself worked', async () => {
patchVergeConfig.mockResolvedValue(undefined)
revalidateQueries.mockRejectedValue(new Error('network gone'))
const { result } = renderHook(() => useSystemProxyState())
await act(async () => {
await expect(result.current.toggleSystemProxy(true)).rejects.toThrow(
'network gone',
)
})
})
it('reports the failure the backend classified, not a revalidation that failed after it', async () => {
patchVergeConfig.mockRejectedValue({
code: 'SYSPROXY_PRIVILEGE_REQUIRED',
detail: 'refused',
})
revalidateQueries.mockRejectedValue(new Error('network gone'))
const { result } = renderHook(() => useSystemProxyState())
await act(async () => {
await expect(result.current.toggleSystemProxy(true)).rejects.toMatchObject({
code: 'SYSPROXY_PRIVILEGE_REQUIRED',
})
})
})
it('revalidates the config it wrote to, not only the two proxy reads', async () => {
patchVergeConfig.mockResolvedValue(undefined)
const { result } = renderHook(() => useSystemProxyState())
await act(async () => {
await result.current.toggleSystemProxy(true)
})
expect(revalidateQueries).toHaveBeenCalledWith([
['getVergeConfig'],
['getSystemProxy'],
['getAutotemProxy'],
])
})
it('drops a click queued behind one that failed', async () => {
let rejectFirst: ((reason: unknown) => void) | undefined
patchVergeConfig.mockImplementationOnce(
() =>
new Promise((_resolve, reject) => {
rejectFirst = reject
}),
)
const { result } = renderHook(() => useSystemProxyState())
let inFlight: Promise<unknown> = Promise.resolve()
await act(async () => {
inFlight = result.current.toggleSystemProxy(true)
void result.current.toggleSystemProxy(false)
rejectFirst?.({ code: 'SYSPROXY_PRIVILEGE_REQUIRED', detail: 'refused' })
await expect(inFlight).rejects.toBeTruthy()
})
expect(patchVergeConfig).toHaveBeenCalledTimes(1)
})
+47 -7
View File
@@ -4,12 +4,20 @@ import { closeAllConnections } from 'tauri-plugin-mihomo-api'
import { useDisplayedMixedPort } from '@/hooks/use-displayed-mixed-port'
import { useVerge } from '@/hooks/use-verge'
import { useSystemData } from '@/providers/app-data-context'
import { getAutotemProxy, getEmbeddedServerPort } from '@/services/cmds'
import { revalidateQueries, useQuery } from '@/services/query-client'
import {
getAutotemProxy,
getEmbeddedServerPort,
patchVergeConfig,
} from '@/services/cmds'
import {
getCacheData,
revalidateQueries,
useQuery,
} from '@/services/query-client'
// 系统代理状态检测统一逻辑
export const useSystemProxyState = () => {
const { verge, mutateVerge, patchVerge } = useVerge()
const { verge, mutateVerge } = useVerge()
const { sysproxy } = useSystemData()
const displayedMixedPort = useDisplayedMixedPort()
const { data: autoproxy } = useQuery({
@@ -23,7 +31,7 @@ export const useSystemProxyState = () => {
queryFn: getEmbeddedServerPort,
})
const { enable_system_proxy, proxy_auto_config, proxy_host } = verge ?? {}
const { proxy_auto_config, proxy_host } = verge ?? {}
// OS 实际状态:enable + 地址匹配本应用
const indicator = (() => {
@@ -43,6 +51,10 @@ export const useSystemProxyState = () => {
const busyRef = useRef(false)
const toggleSystemProxy = async (enabled: boolean) => {
// Roll failed optimistic writes back to the latest confirmed state.
let confirmed =
getCacheData<IVergeConfig>(['getVergeConfig'])?.enable_system_proxy ??
false
mutateVerge(
(prev) => (prev ? { ...prev, enable_system_proxy: enabled } : prev),
false,
@@ -52,18 +64,47 @@ export const useSystemProxyState = () => {
if (busyRef.current) return
busyRef.current = true
let failed = false
try {
while (pendingRef.current !== null) {
const target = pendingRef.current
pendingRef.current = null
await patchVerge({ enable_system_proxy: target })
// Revalidate once below so a refetch failure cannot look like a patch failure.
await patchVergeConfig({ enable_system_proxy: target })
confirmed = target
if (!target && verge?.auto_close_connection) {
await closeAllConnections().catch(() => {})
}
}
} catch (error) {
failed = true
mutateVerge(
(prev) => (prev ? { ...prev, enable_system_proxy: confirmed } : prev),
false,
)
// Queued requests assumed the failed state was reached.
pendingRef.current = null
throw error
} finally {
busyRef.current = false
await revalidateQueries([['getSystemProxy'], ['getAutotemProxy']])
const revalidated = revalidateQueries([
['getVergeConfig'],
['getSystemProxy'],
['getAutotemProxy'],
])
if (failed) {
// Preserve the classified toggle failure.
try {
await revalidated
} catch (error) {
console.warn(
'[system-proxy] revalidating after a failed toggle failed too:',
error,
)
}
} else {
await revalidated
}
}
}
@@ -72,7 +113,6 @@ export const useSystemProxyState = () => {
return {
indicator,
configState: enable_system_proxy ?? false,
toggleSystemProxy,
invalidateProxyState,
}