mirror of
https://github.com/clash-verge-rev/clash-verge-rev.git
synced 2026-11-08 19:22:44 +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:
@@ -143,7 +143,8 @@ export const ProxyTunCard: FC = () => {
|
||||
|
||||
const { verge } = useVerge()
|
||||
const { isTunModeAvailable } = useSystemState()
|
||||
const { configState: systemProxyConfigState } = useSystemProxyState()
|
||||
// Display the observed OS state, not the requested configuration.
|
||||
const { indicator: systemProxyIndicator } = useSystemProxyState()
|
||||
|
||||
const { enable_tun_mode } = verge ?? {}
|
||||
|
||||
@@ -159,7 +160,7 @@ export const ProxyTunCard: FC = () => {
|
||||
const tabDescription = useMemo(() => {
|
||||
if (activeTab === 'system') {
|
||||
return {
|
||||
text: systemProxyConfigState
|
||||
text: systemProxyIndicator
|
||||
? t('home.components.proxyTun.status.systemProxyEnabled')
|
||||
: t('home.components.proxyTun.status.systemProxyDisabled'),
|
||||
tooltip: t('home.components.proxyTun.tooltips.systemProxy'),
|
||||
@@ -174,13 +175,7 @@ export const ProxyTunCard: FC = () => {
|
||||
tooltip: t('home.components.proxyTun.tooltips.tunMode'),
|
||||
}
|
||||
}
|
||||
}, [
|
||||
activeTab,
|
||||
systemProxyConfigState,
|
||||
enable_tun_mode,
|
||||
isTunModeAvailable,
|
||||
t,
|
||||
])
|
||||
}, [activeTab, systemProxyIndicator, enable_tun_mode, isTunModeAvailable, t])
|
||||
|
||||
return (
|
||||
<Box sx={{ display: 'flex', flexDirection: 'column', width: '100%' }}>
|
||||
@@ -199,7 +194,7 @@ export const ProxyTunCard: FC = () => {
|
||||
onClick={() => handleTabChange('system')}
|
||||
icon={ComputerRounded}
|
||||
label={t('settings.sections.system.toggles.systemProxy')}
|
||||
hasIndicator={systemProxyConfigState}
|
||||
hasIndicator={systemProxyIndicator}
|
||||
/>
|
||||
<TabButton
|
||||
isActive={activeTab === 'tun'}
|
||||
|
||||
@@ -0,0 +1,173 @@
|
||||
// @vitest-environment jsdom
|
||||
import {
|
||||
cleanup,
|
||||
fireEvent,
|
||||
render,
|
||||
screen,
|
||||
waitFor,
|
||||
} from '@testing-library/react'
|
||||
import i18next from 'i18next'
|
||||
import { initReactI18next } from 'react-i18next'
|
||||
import { afterEach, beforeAll, expect, it, vi } from 'vitest'
|
||||
|
||||
import {
|
||||
getSnapshotNotices,
|
||||
hideNotice,
|
||||
showNotice,
|
||||
} from '@/services/notice-service'
|
||||
|
||||
import { NoticeManager } from './notice-manager'
|
||||
|
||||
const writeText = vi.fn((_text: string) => Promise.resolve())
|
||||
const restartCore = vi.hoisted(() => vi.fn(() => Promise.resolve()))
|
||||
const installService = vi.hoisted(() => vi.fn(() => Promise.resolve()))
|
||||
const getRuntimeState = vi.hoisted(() => vi.fn())
|
||||
|
||||
vi.mock('@/services/cmds', () => ({
|
||||
restartCore,
|
||||
installService,
|
||||
getRuntimeState,
|
||||
}))
|
||||
vi.mock('@/utils/get-system', () => ({ default: () => 'macos' }))
|
||||
|
||||
beforeAll(async () => {
|
||||
await i18next.use(initReactI18next).init({
|
||||
lng: 'en',
|
||||
resources: {
|
||||
en: {
|
||||
translation: {
|
||||
settings: {
|
||||
modals: {
|
||||
backup: {
|
||||
messages: { backupFailed: 'Backup failed: {{error}}' },
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
interpolation: { escapeValue: false },
|
||||
})
|
||||
Object.defineProperty(navigator, 'clipboard', {
|
||||
value: { writeText },
|
||||
configurable: true,
|
||||
})
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
restartCore.mockClear()
|
||||
restartCore.mockImplementation(() => Promise.resolve())
|
||||
installService.mockClear()
|
||||
installService.mockImplementation(() => Promise.resolve())
|
||||
getRuntimeState.mockReset()
|
||||
getRuntimeState.mockResolvedValue({ mode: 'Service', serviceUsable: true })
|
||||
cleanup()
|
||||
getSnapshotNotices().forEach((notice) => hideNotice(notice.id))
|
||||
writeText.mockClear()
|
||||
})
|
||||
|
||||
const noticeText = () => screen.getByRole('alert').textContent ?? ''
|
||||
|
||||
it('renders a failure detail that fits, in full', () => {
|
||||
showNotice.error({ code: 'CORE_START_FAILED', detail: 'connection refused' })
|
||||
render(<NoticeManager />)
|
||||
|
||||
expect(noticeText()).toContain('connection refused')
|
||||
})
|
||||
|
||||
it('shortens an unbounded detail', () => {
|
||||
showNotice.error({
|
||||
code: 'SERVICE_INSTALL_FAILED',
|
||||
detail: `${'x'.repeat(4000)} tail`,
|
||||
})
|
||||
render(<NoticeManager />)
|
||||
|
||||
expect(noticeText().length).toBeLessThanOrEqual(501)
|
||||
expect(noticeText()).not.toContain('tail')
|
||||
expect(noticeText()).toContain('…')
|
||||
})
|
||||
|
||||
it('shortens a detail a caller interpolated into its own message', () => {
|
||||
showNotice.error('profiles.page.feedback.notices.emergencyRefreshFailed', {
|
||||
message: 'y'.repeat(4000),
|
||||
})
|
||||
render(<NoticeManager />)
|
||||
|
||||
expect(noticeText().length).toBeLessThanOrEqual(501)
|
||||
expect(noticeText()).toContain('…')
|
||||
})
|
||||
|
||||
it('renders a failure a caller interpolated, not [object Object]', () => {
|
||||
showNotice.error('settings.modals.backup.messages.backupFailed', {
|
||||
error: { code: 'BACKUP_FAILED', detail: 'webdav returned 401' },
|
||||
})
|
||||
render(<NoticeManager />)
|
||||
|
||||
expect(noticeText()).toBe('Backup failed: webdav returned 401')
|
||||
})
|
||||
|
||||
it('renders a failure inside a descriptor, not [object Object]', () => {
|
||||
showNotice.error({
|
||||
key: 'settings.modals.backup.messages.backupFailed',
|
||||
params: { error: { code: 'BACKUP_FAILED', detail: 'webdav returned 401' } },
|
||||
})
|
||||
render(<NoticeManager />)
|
||||
|
||||
expect(noticeText()).toBe('Backup failed: webdav returned 401')
|
||||
})
|
||||
|
||||
it('leaves the ordinary lifetime alone where there is nothing to offer', () => {
|
||||
showNotice.error({ code: 'CORE_START_FAILED', detail: 'connection refused' })
|
||||
|
||||
expect(getSnapshotNotices().at(-1)?.duration).toBeGreaterThan(0)
|
||||
})
|
||||
|
||||
it('finds the code a caller interpolated into its own message', () => {
|
||||
showNotice.error('settings.modals.backup.messages.backupFailed', {
|
||||
error: { code: 'SYSPROXY_GUARD_STOPPED', detail: 'the guard gave up' },
|
||||
})
|
||||
|
||||
expect(getSnapshotNotices().at(-1)?.code).toBe('SYSPROXY_GUARD_STOPPED')
|
||||
})
|
||||
it('shows one notice per code, replacing rather than stacking', async () => {
|
||||
showNotice.error({ code: 'SYSPROXY_GUARD_STOPPED', detail: 'first' })
|
||||
showNotice.error({ code: 'SYSPROXY_GUARD_STOPPED', detail: 'second' })
|
||||
render(<NoticeManager />)
|
||||
|
||||
expect(screen.getAllByRole('alert')).toHaveLength(1)
|
||||
expect(screen.getByRole('alert').textContent).toContain('second')
|
||||
})
|
||||
|
||||
it('remembers which way the user was asking, for whoever acts on it next', () => {
|
||||
showNotice.error({
|
||||
code: 'SYSPROXY_GUARD_STOPPED',
|
||||
detail: 'admin privileges required to modify system proxy',
|
||||
operation: 'systemProxyEnable',
|
||||
})
|
||||
|
||||
expect(getSnapshotNotices().at(-1)?.operation).toBe('systemProxyEnable')
|
||||
})
|
||||
|
||||
it('copies the whole detail, not the shortened one', async () => {
|
||||
const detail = `${'x'.repeat(4000)} tail`
|
||||
showNotice.error({ code: 'SERVICE_INSTALL_FAILED', detail })
|
||||
render(<NoticeManager />)
|
||||
|
||||
fireEvent.contextMenu(screen.getByRole('alert'))
|
||||
|
||||
await waitFor(() => expect(writeText).toHaveBeenCalledOnce())
|
||||
expect(writeText).toHaveBeenCalledWith(detail)
|
||||
})
|
||||
|
||||
it('copies the whole message when the caller interpolated the detail', async () => {
|
||||
const detail = 'y'.repeat(4000)
|
||||
showNotice.error('profiles.page.feedback.notices.emergencyRefreshFailed', {
|
||||
message: detail,
|
||||
})
|
||||
render(<NoticeManager />)
|
||||
|
||||
fireEvent.contextMenu(screen.getByRole('alert'))
|
||||
|
||||
await waitFor(() => expect(writeText).toHaveBeenCalledOnce())
|
||||
expect(writeText.mock.calls[0]?.[0]).toContain(detail)
|
||||
})
|
||||
@@ -4,12 +4,14 @@ import {
|
||||
Alert,
|
||||
IconButton,
|
||||
Box,
|
||||
Stack,
|
||||
type SnackbarOrigin,
|
||||
} from '@mui/material'
|
||||
import React, { useCallback, useMemo, useSyncExternalStore } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
|
||||
import {
|
||||
boundNoticeText,
|
||||
subscribeNotices,
|
||||
hideNotice,
|
||||
getSnapshotNotices,
|
||||
@@ -43,14 +45,31 @@ const getAnchorOrigin = (position: NoticePosition): SnackbarOrigin => {
|
||||
return { vertical, horizontal }
|
||||
}
|
||||
|
||||
/** Resolve notice text, bounding display output but not clipboard content. */
|
||||
const resolveNoticeMessage = (
|
||||
notice: NoticeItem,
|
||||
t: TranslationFn,
|
||||
options?: { bounded?: boolean },
|
||||
): React.ReactNode => {
|
||||
const i18n = notice.i18n
|
||||
if (!i18n) return notice.message
|
||||
const bound = (text: React.ReactNode): React.ReactNode =>
|
||||
options?.bounded === false || typeof text !== 'string'
|
||||
? text
|
||||
: boundNoticeText(text)
|
||||
|
||||
const params = (i18n.params ?? {}) as Record<string, unknown>
|
||||
const i18n = notice.i18n
|
||||
if (!i18n) return bound(notice.message)
|
||||
|
||||
const source = (i18n.params ?? {}) as Record<string, unknown>
|
||||
// Bound both parameters and their final interpolation.
|
||||
const params =
|
||||
options?.bounded === false
|
||||
? source
|
||||
: Object.fromEntries(
|
||||
Object.entries(source).map(([key, value]) => [
|
||||
key,
|
||||
typeof value === 'string' ? boundNoticeText(value) : value,
|
||||
]),
|
||||
)
|
||||
const { prefixKey, prefixParams, prefix, message, ...restParams } = params
|
||||
|
||||
const prefixKeyParams =
|
||||
@@ -78,12 +97,14 @@ const resolveNoticeMessage = (
|
||||
? `${resolvedPrefix} ${messageStr}`
|
||||
: messageStr
|
||||
|
||||
return t(i18n.key as TranslationKey, {
|
||||
defaultValue,
|
||||
...restParams,
|
||||
...(resolvedPrefix !== undefined ? { prefix: resolvedPrefix } : {}),
|
||||
...(messageStr !== undefined ? { message: messageStr } : {}),
|
||||
})
|
||||
return bound(
|
||||
t(i18n.key as TranslationKey, {
|
||||
defaultValue,
|
||||
...restParams,
|
||||
...(resolvedPrefix !== undefined ? { prefix: resolvedPrefix } : {}),
|
||||
...(messageStr !== undefined ? { message: messageStr } : {}),
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
const extractNoticeCopyText = (input: unknown): string | undefined => {
|
||||
@@ -120,8 +141,9 @@ const resolveNoticeCopyText = (
|
||||
}
|
||||
|
||||
return (
|
||||
extractNoticeCopyText(resolveNoticeMessage(notice, t)) ??
|
||||
extractNoticeCopyText(notice.message)
|
||||
extractNoticeCopyText(
|
||||
resolveNoticeMessage(notice, t, { bounded: false }),
|
||||
) ?? extractNoticeCopyText(notice.message)
|
||||
)
|
||||
}
|
||||
|
||||
@@ -202,13 +224,19 @@ export const NoticeManager: React.FC<NoticeManagerProps> = ({ position }) => {
|
||||
void handleNoticeCopy(notice)
|
||||
}}
|
||||
action={
|
||||
<IconButton
|
||||
size="small"
|
||||
color="inherit"
|
||||
onClick={() => handleClose(notice.id)}
|
||||
<Stack
|
||||
direction="row"
|
||||
spacing={0.5}
|
||||
sx={{ alignItems: 'center' }}
|
||||
>
|
||||
<CloseRounded fontSize="inherit" />
|
||||
</IconButton>
|
||||
<IconButton
|
||||
size="small"
|
||||
color="inherit"
|
||||
onClick={() => handleClose(notice.id)}
|
||||
>
|
||||
<CloseRounded fontSize="inherit" />
|
||||
</IconButton>
|
||||
</Stack>
|
||||
}
|
||||
>
|
||||
{resolveNoticeMessage(notice, t)}
|
||||
|
||||
@@ -0,0 +1,350 @@
|
||||
// @vitest-environment jsdom
|
||||
import {
|
||||
act,
|
||||
cleanup,
|
||||
fireEvent,
|
||||
render,
|
||||
screen,
|
||||
waitFor,
|
||||
} from '@testing-library/react'
|
||||
import i18next from 'i18next'
|
||||
import { initReactI18next } from 'react-i18next'
|
||||
import { afterEach, beforeAll, expect, it, vi } from 'vitest'
|
||||
|
||||
import type { PendingFailure } from '@/services/cmds'
|
||||
import { getSnapshotNotices, hideNotice } from '@/services/notice-service'
|
||||
import { clearServiceRequest, requestService } from '@/services/service-request'
|
||||
|
||||
const reported = (key: string) =>
|
||||
getSnapshotNotices().some(
|
||||
(notice) =>
|
||||
notice.i18n?.key === key ||
|
||||
Object.values(notice.i18n?.params ?? {}).some(
|
||||
(param) =>
|
||||
typeof param === 'object' &&
|
||||
param !== null &&
|
||||
'key' in param &&
|
||||
(param as { key?: unknown }).key === key,
|
||||
),
|
||||
)
|
||||
|
||||
import { SysproxyPrivilegeDialog } from './sysproxy-privilege-dialog'
|
||||
|
||||
const restartCore = vi.hoisted(() => vi.fn(() => Promise.resolve()))
|
||||
const installService = vi.hoisted(() => vi.fn(() => Promise.resolve()))
|
||||
const getRuntimeState = vi.hoisted(() => vi.fn())
|
||||
const getPendingFailures = vi.hoisted(() => vi.fn())
|
||||
const patchVergeConfig = vi.hoisted(() => vi.fn(() => Promise.resolve()))
|
||||
const onFocusChanged = vi.hoisted(() => vi.fn(() => Promise.resolve(() => {})))
|
||||
|
||||
vi.mock('@/services/cmds', () => ({
|
||||
restartCore,
|
||||
installService,
|
||||
getRuntimeState,
|
||||
getPendingFailures,
|
||||
patchVergeConfig,
|
||||
}))
|
||||
vi.mock('@tauri-apps/api/window', () => ({
|
||||
getCurrentWindow: () => ({ onFocusChanged }),
|
||||
}))
|
||||
|
||||
let onSubscribed: (() => void) | undefined
|
||||
vi.mock('@/services/events', () => ({
|
||||
subscribeVergeEvents: (
|
||||
_handlers: Record<string, () => void>,
|
||||
subscribed?: () => void,
|
||||
) => {
|
||||
onSubscribed = subscribed
|
||||
return () => {}
|
||||
},
|
||||
}))
|
||||
|
||||
const failure = (
|
||||
code: string,
|
||||
operation: PendingFailure['operation'] = 'systemProxyEnable',
|
||||
): PendingFailure => ({
|
||||
code,
|
||||
detail: 'admin privileges required to modify system proxy',
|
||||
operation,
|
||||
sequence: 1,
|
||||
})
|
||||
|
||||
beforeAll(async () => {
|
||||
await i18next.use(initReactI18next).init({
|
||||
lng: 'en',
|
||||
resources: { en: { translation: {} } },
|
||||
interpolation: { escapeValue: false },
|
||||
})
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
restartCore.mockClear()
|
||||
restartCore.mockImplementation(() => Promise.resolve())
|
||||
installService.mockClear()
|
||||
installService.mockImplementation(() => Promise.resolve())
|
||||
getRuntimeState.mockReset()
|
||||
getRuntimeState.mockResolvedValue({ mode: 'Service', serviceUsable: true })
|
||||
getPendingFailures.mockReset()
|
||||
patchVergeConfig.mockClear()
|
||||
patchVergeConfig.mockImplementation(() => Promise.resolve())
|
||||
onSubscribed = undefined
|
||||
clearServiceRequest()
|
||||
cleanup()
|
||||
getSnapshotNotices().forEach((notice) => hideNotice(notice.id))
|
||||
})
|
||||
|
||||
const showing = async (
|
||||
code: string,
|
||||
operation: PendingFailure['operation'] = 'systemProxyEnable',
|
||||
) => {
|
||||
getPendingFailures.mockResolvedValue([failure(code, operation)])
|
||||
render(<SysproxyPrivilegeDialog />)
|
||||
onSubscribed?.()
|
||||
await screen.findByRole('dialog')
|
||||
}
|
||||
|
||||
const clickPrimary = (name: string) =>
|
||||
fireEvent.click(screen.getByRole('button', { name }))
|
||||
|
||||
it('offers to install the service when the write was refused', async () => {
|
||||
await showing('SYSPROXY_PRIVILEGE_REQUIRED')
|
||||
|
||||
expect(
|
||||
screen.getByRole('button', {
|
||||
name: 'settings.sections.proxyControl.actions.installService',
|
||||
}),
|
||||
).toBeTruthy()
|
||||
})
|
||||
|
||||
it('offers only a restart when the service is already there', async () => {
|
||||
await showing('SYSPROXY_SIDECAR_WHILE_SERVICE_READY')
|
||||
|
||||
expect(
|
||||
screen.getByRole('button', {
|
||||
name: 'settings.sections.proxyControl.actions.switchToServiceMode',
|
||||
}),
|
||||
).toBeTruthy()
|
||||
expect(
|
||||
screen.queryByRole('button', {
|
||||
name: 'settings.sections.proxyControl.actions.installService',
|
||||
}),
|
||||
).toBeNull()
|
||||
})
|
||||
|
||||
it('installs the service, restarts into it, and makes the request again', async () => {
|
||||
await showing('SYSPROXY_PRIVILEGE_REQUIRED')
|
||||
|
||||
clickPrimary('settings.sections.proxyControl.actions.installService')
|
||||
|
||||
await waitFor(() => expect(installService).toHaveBeenCalledOnce())
|
||||
await waitFor(() => expect(restartCore).toHaveBeenCalledOnce())
|
||||
await waitFor(() =>
|
||||
expect(patchVergeConfig).toHaveBeenCalledWith({
|
||||
enable_system_proxy: true,
|
||||
}),
|
||||
)
|
||||
await waitFor(() =>
|
||||
expect(
|
||||
reported(
|
||||
'settings.sections.proxyControl.messages.installedProxyRestored',
|
||||
),
|
||||
).toBe(true),
|
||||
)
|
||||
})
|
||||
|
||||
it('replays the direction that was asked for, not always “on”', async () => {
|
||||
await showing('SYSPROXY_PRIVILEGE_REQUIRED', 'systemProxyDisable')
|
||||
|
||||
clickPrimary('settings.sections.proxyControl.actions.installService')
|
||||
|
||||
await waitFor(() =>
|
||||
expect(patchVergeConfig).toHaveBeenCalledWith({
|
||||
enable_system_proxy: false,
|
||||
}),
|
||||
)
|
||||
})
|
||||
|
||||
it('changes nothing when nobody asked for a proxy state', async () => {
|
||||
await showing('SYSPROXY_PRIVILEGE_REQUIRED', 'systemProxyRestore')
|
||||
|
||||
clickPrimary('settings.sections.proxyControl.actions.installService')
|
||||
|
||||
await waitFor(() => expect(restartCore).toHaveBeenCalledOnce())
|
||||
expect(patchVergeConfig).not.toHaveBeenCalled()
|
||||
await waitFor(() =>
|
||||
expect(
|
||||
reported('settings.sections.proxyControl.messages.installedCheckProxy'),
|
||||
).toBe(true),
|
||||
)
|
||||
})
|
||||
|
||||
it('does not install again when only the restart is needed', async () => {
|
||||
await showing('SYSPROXY_SIDECAR_WHILE_SERVICE_READY')
|
||||
|
||||
clickPrimary('settings.sections.proxyControl.actions.switchToServiceMode')
|
||||
|
||||
await waitFor(() => expect(restartCore).toHaveBeenCalledOnce())
|
||||
expect(installService).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('checks what actually happened rather than trusting the restart', async () => {
|
||||
getRuntimeState.mockResolvedValue({ mode: 'Sidecar', serviceUsable: true })
|
||||
await showing('SYSPROXY_PRIVILEGE_REQUIRED')
|
||||
|
||||
clickPrimary('settings.sections.proxyControl.actions.installService')
|
||||
|
||||
await waitFor(() =>
|
||||
expect(
|
||||
reported(
|
||||
'settings.sections.proxyControl.messages.installedCoreNotOnService',
|
||||
),
|
||||
).toBe(true),
|
||||
)
|
||||
})
|
||||
|
||||
const deferred = () => {
|
||||
let resolve!: () => void
|
||||
const promise = new Promise<void>((r) => {
|
||||
resolve = r
|
||||
})
|
||||
return { promise, resolve }
|
||||
}
|
||||
|
||||
it('says which part of the wait it is in, rather than looking stuck', async () => {
|
||||
const installing = deferred()
|
||||
const restarting = deferred()
|
||||
const applying = deferred()
|
||||
installService.mockImplementation(() => installing.promise)
|
||||
restartCore.mockImplementation(() => restarting.promise)
|
||||
patchVergeConfig.mockImplementation(() => applying.promise)
|
||||
|
||||
await showing('SYSPROXY_PRIVILEGE_REQUIRED')
|
||||
clickPrimary('settings.sections.proxyControl.actions.installService')
|
||||
|
||||
await screen.findByText('layout.components.sysproxyPrivilege.installing')
|
||||
installing.resolve()
|
||||
|
||||
await screen.findByText('layout.components.sysproxyPrivilege.restarting')
|
||||
restarting.resolve()
|
||||
|
||||
await screen.findByText('layout.components.sysproxyPrivilege.applying')
|
||||
applying.resolve()
|
||||
|
||||
await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull())
|
||||
})
|
||||
|
||||
it('does not claim to be installing when only a restart is needed', async () => {
|
||||
const restarting = deferred()
|
||||
restartCore.mockImplementation(() => restarting.promise)
|
||||
|
||||
await showing('SYSPROXY_SIDECAR_WHILE_SERVICE_READY')
|
||||
clickPrimary('settings.sections.proxyControl.actions.switchToServiceMode')
|
||||
|
||||
await screen.findByText('layout.components.sysproxyPrivilege.restarting')
|
||||
expect(
|
||||
screen.queryByText('layout.components.sysproxyPrivilege.installing'),
|
||||
).toBeNull()
|
||||
restarting.resolve()
|
||||
})
|
||||
|
||||
it('offers no way out while the installer is holding a password prompt', async () => {
|
||||
const installing = deferred()
|
||||
installService.mockImplementation(() => installing.promise)
|
||||
|
||||
await showing('SYSPROXY_PRIVILEGE_REQUIRED')
|
||||
clickPrimary('settings.sections.proxyControl.actions.installService')
|
||||
|
||||
await screen.findByText('layout.components.sysproxyPrivilege.installing')
|
||||
expect(
|
||||
screen.queryByRole('button', {
|
||||
name: 'layout.components.sysproxyPrivilege.later',
|
||||
}),
|
||||
).toBeNull()
|
||||
installing.resolve()
|
||||
})
|
||||
|
||||
it('closes once the core is on the service, whatever the table still says', async () => {
|
||||
await showing('SYSPROXY_PRIVILEGE_REQUIRED')
|
||||
|
||||
clickPrimary('settings.sections.proxyControl.actions.installService')
|
||||
|
||||
await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull())
|
||||
})
|
||||
|
||||
it('stays open when the core did not reach the service', async () => {
|
||||
getRuntimeState.mockResolvedValue({ mode: 'Sidecar', serviceUsable: false })
|
||||
await showing('SYSPROXY_PRIVILEGE_REQUIRED')
|
||||
|
||||
clickPrimary('settings.sections.proxyControl.actions.installService')
|
||||
|
||||
await waitFor(() => expect(restartCore).toHaveBeenCalledOnce())
|
||||
expect(screen.getByRole('dialog')).toBeTruthy()
|
||||
})
|
||||
|
||||
it('does not go on to restart when the install itself failed', async () => {
|
||||
installService.mockRejectedValue({
|
||||
code: 'SERVICE_INSTALL_FAILED',
|
||||
detail: 'user cancelled',
|
||||
})
|
||||
await showing('SYSPROXY_PRIVILEGE_REQUIRED')
|
||||
|
||||
clickPrimary('settings.sections.proxyControl.actions.installService')
|
||||
|
||||
await waitFor(() => expect(installService).toHaveBeenCalledOnce())
|
||||
expect(restartCore).not.toHaveBeenCalled()
|
||||
expect(getRuntimeState).not.toHaveBeenCalled()
|
||||
expect(screen.getByRole('dialog')).toBeTruthy()
|
||||
})
|
||||
|
||||
it('closes on “later” without touching the machine', async () => {
|
||||
await showing('SYSPROXY_PRIVILEGE_REQUIRED')
|
||||
|
||||
clickPrimary('layout.components.sysproxyPrivilege.later')
|
||||
|
||||
await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull())
|
||||
expect(installService).not.toHaveBeenCalled()
|
||||
expect(restartCore).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('answers a switch that asked outright, with no failure to go on', async () => {
|
||||
getPendingFailures.mockResolvedValue([])
|
||||
render(<SysproxyPrivilegeDialog />)
|
||||
onSubscribed?.()
|
||||
|
||||
act(() =>
|
||||
requestService({
|
||||
reason: 'tunNeedsService',
|
||||
restore: { enable_tun_mode: true },
|
||||
}),
|
||||
)
|
||||
|
||||
await screen.findByText('layout.components.sysproxyPrivilege.tunMessage')
|
||||
clickPrimary('settings.sections.proxyControl.actions.installService')
|
||||
|
||||
await waitFor(() => expect(installService).toHaveBeenCalledOnce())
|
||||
await waitFor(() =>
|
||||
expect(patchVergeConfig).toHaveBeenCalledWith({ enable_tun_mode: true }),
|
||||
)
|
||||
await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull())
|
||||
})
|
||||
|
||||
it('shows what the user is doing now over what the table still holds', async () => {
|
||||
await showing('SYSPROXY_PRIVILEGE_REQUIRED')
|
||||
|
||||
act(() => requestService({ reason: 'tunNeedsService' }))
|
||||
|
||||
await screen.findByText('layout.components.sysproxyPrivilege.tunMessage')
|
||||
})
|
||||
|
||||
it('changes nothing when a switch asked without saying what for', async () => {
|
||||
getPendingFailures.mockResolvedValue([])
|
||||
render(<SysproxyPrivilegeDialog />)
|
||||
onSubscribed?.()
|
||||
|
||||
act(() => requestService({ reason: 'tunNeedsService' }))
|
||||
await screen.findByRole('dialog')
|
||||
clickPrimary('settings.sections.proxyControl.actions.installService')
|
||||
|
||||
await waitFor(() => expect(restartCore).toHaveBeenCalledOnce())
|
||||
expect(patchVergeConfig).not.toHaveBeenCalled()
|
||||
})
|
||||
@@ -0,0 +1,155 @@
|
||||
import { Alert, LinearProgress, Typography } from '@mui/material'
|
||||
import { useState, useSyncExternalStore } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
|
||||
import { BaseDialog } from '@/components/base'
|
||||
import { useDialogFailure } from '@/pages/_layout/hooks'
|
||||
import {
|
||||
getRuntimeState,
|
||||
installService,
|
||||
patchVergeConfig,
|
||||
restartCore,
|
||||
type FailedOperation,
|
||||
type PendingFailure,
|
||||
} from '@/services/cmds'
|
||||
import { showNotice } from '@/services/notice-service'
|
||||
import {
|
||||
clearServiceRequest,
|
||||
getServiceRequest,
|
||||
subscribeServiceRequest,
|
||||
type ServiceRequest,
|
||||
type ServiceRequestReason,
|
||||
} from '@/services/service-request'
|
||||
|
||||
type Remedy = 'installAndRestart' | 'restartOnly'
|
||||
|
||||
const remedyFor = (reason: ServiceRequestReason): Remedy =>
|
||||
reason === 'sysproxySidecarReady' ? 'restartOnly' : 'installAndRestart'
|
||||
|
||||
const EXPLANATION = {
|
||||
sysproxyRefused: 'layout.components.sysproxyPrivilege.message',
|
||||
sysproxySidecarReady:
|
||||
'layout.components.sysproxyPrivilege.serviceReadyMessage',
|
||||
tunNeedsService: 'layout.components.sysproxyPrivilege.tunMessage',
|
||||
} as const
|
||||
|
||||
const TITLE = {
|
||||
sysproxyRefused: 'layout.components.sysproxyPrivilege.title',
|
||||
sysproxySidecarReady: 'layout.components.sysproxyPrivilege.title',
|
||||
tunNeedsService: 'layout.components.sysproxyPrivilege.tunTitle',
|
||||
} as const
|
||||
|
||||
const stateToRestore = (
|
||||
operation: FailedOperation,
|
||||
): Partial<IVergeConfig> | undefined => {
|
||||
switch (operation) {
|
||||
case 'systemProxyEnable':
|
||||
return { enable_system_proxy: true }
|
||||
case 'systemProxyDisable':
|
||||
return { enable_system_proxy: false }
|
||||
case 'systemProxyRestore':
|
||||
case 'systemProxyGuard':
|
||||
return undefined
|
||||
}
|
||||
}
|
||||
|
||||
const asServiceRequest = (failure: PendingFailure): ServiceRequest => ({
|
||||
reason:
|
||||
failure.code === 'SYSPROXY_SIDECAR_WHILE_SERVICE_READY'
|
||||
? 'sysproxySidecarReady'
|
||||
: 'sysproxyRefused',
|
||||
restore: stateToRestore(failure.operation),
|
||||
})
|
||||
|
||||
type Step = 'idle' | 'installing' | 'restarting' | 'applying'
|
||||
|
||||
const STEP_MESSAGE = {
|
||||
installing: 'layout.components.sysproxyPrivilege.installing',
|
||||
restarting: 'layout.components.sysproxyPrivilege.restarting',
|
||||
applying: 'layout.components.sysproxyPrivilege.applying',
|
||||
} as const
|
||||
|
||||
/** Guide recovery from a refused system-proxy write. */
|
||||
export const SysproxyPrivilegeDialog = () => {
|
||||
const { t } = useTranslation()
|
||||
const { failure, dismiss } = useDialogFailure()
|
||||
const asked = useSyncExternalStore(subscribeServiceRequest, getServiceRequest)
|
||||
const [step, setStep] = useState<Step>('idle')
|
||||
const loading = step !== 'idle'
|
||||
|
||||
// Prefer the request the user just made over a pending failure.
|
||||
const request = asked ?? (failure ? asServiceRequest(failure) : null)
|
||||
|
||||
const reason = request?.reason ?? 'sysproxyRefused'
|
||||
const remedy = remedyFor(reason)
|
||||
const restoring = request?.restore
|
||||
|
||||
const close = () => {
|
||||
clearServiceRequest()
|
||||
dismiss()
|
||||
}
|
||||
|
||||
const handleFix = async () => {
|
||||
try {
|
||||
if (remedy === 'installAndRestart') {
|
||||
setStep('installing')
|
||||
await installService()
|
||||
}
|
||||
setStep('restarting')
|
||||
await restartCore()
|
||||
|
||||
// Verify that restart actually moved the core into the service.
|
||||
const runState = await getRuntimeState()
|
||||
if (runState.mode === 'Service') {
|
||||
// Retry the original request now that the service can apply it.
|
||||
if (restoring !== undefined) {
|
||||
setStep('applying')
|
||||
await patchVergeConfig(restoring)
|
||||
}
|
||||
showNotice.success(
|
||||
restoring === undefined
|
||||
? 'settings.sections.proxyControl.messages.installedCheckProxy'
|
||||
: 'settings.sections.proxyControl.messages.installedProxyRestored',
|
||||
)
|
||||
close()
|
||||
} else {
|
||||
showNotice.error(
|
||||
'settings.sections.proxyControl.messages.installedCoreNotOnService',
|
||||
)
|
||||
}
|
||||
} catch (error) {
|
||||
showNotice.error(error)
|
||||
} finally {
|
||||
setStep('idle')
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<BaseDialog
|
||||
open={Boolean(request)}
|
||||
title={t(TITLE[reason])}
|
||||
okBtn={t(
|
||||
remedy === 'installAndRestart'
|
||||
? 'settings.sections.proxyControl.actions.installService'
|
||||
: 'settings.sections.proxyControl.actions.switchToServiceMode',
|
||||
)}
|
||||
cancelBtn={t('layout.components.sysproxyPrivilege.later')}
|
||||
// Keep the primary spinner visible; only cancellation is unavailable.
|
||||
disableCancel={loading}
|
||||
loading={loading}
|
||||
onOk={() => void handleFix()}
|
||||
onCancel={close}
|
||||
onClose={close}
|
||||
>
|
||||
<Alert severity={loading ? 'info' : 'warning'} sx={{ mb: 1.5 }}>
|
||||
{t(step !== 'idle' ? STEP_MESSAGE[step] : EXPLANATION[reason])}
|
||||
</Alert>
|
||||
{loading && <LinearProgress />}
|
||||
{!loading && reason === 'sysproxyRefused' && (
|
||||
<Typography variant="body2" color="text.secondary">
|
||||
{t('layout.components.sysproxyPrivilege.alternative')}
|
||||
</Typography>
|
||||
)}
|
||||
</BaseDialog>
|
||||
)
|
||||
}
|
||||
@@ -15,7 +15,7 @@ import { useTranslation } from 'react-i18next'
|
||||
|
||||
import { useVerge } from '@/hooks/use-verge'
|
||||
import { saveWebdavConfig, createWebdavBackup } from '@/services/cmds'
|
||||
import { showNotice } from '@/services/notice-service'
|
||||
import { errorDetail, showNotice } from '@/services/notice-service'
|
||||
import {
|
||||
buildWebdavSignature,
|
||||
getWebdavStatus,
|
||||
@@ -138,7 +138,7 @@ export const BackupConfigViewer = memo(
|
||||
} catch (error) {
|
||||
showNotice.error(
|
||||
'settings.modals.backup.messages.webdavConfigSaveFailed',
|
||||
{ error },
|
||||
{ error: errorDetail(error) },
|
||||
3000,
|
||||
)
|
||||
} finally {
|
||||
|
||||
@@ -19,7 +19,7 @@ import {
|
||||
createWebdavBackup,
|
||||
importLocalBackup,
|
||||
} from '@/services/cmds'
|
||||
import { showNotice } from '@/services/notice-service'
|
||||
import { errorDetail, showNotice } from '@/services/notice-service'
|
||||
import { buildWebdavSignature, setWebdavStatus } from '@/services/webdav-status'
|
||||
|
||||
import { AutoBackupSettings } from './auto-backup-settings'
|
||||
@@ -68,7 +68,7 @@ export function BackupViewer({ ref }: { ref?: Ref<DialogRef> }) {
|
||||
target === 'local'
|
||||
? 'settings.modals.backup.messages.localBackupFailed'
|
||||
: 'settings.modals.backup.messages.backupFailed',
|
||||
target === 'local' ? undefined : { error },
|
||||
target === 'local' ? undefined : { error: errorDetail(error) },
|
||||
)
|
||||
if (target === 'webdav') {
|
||||
setWebdavStatus(webdavSignature, 'failed')
|
||||
@@ -93,7 +93,7 @@ export function BackupViewer({ ref }: { ref?: Ref<DialogRef> }) {
|
||||
console.error(error)
|
||||
showNotice.error(
|
||||
'settings.modals.backup.messages.localBackupImportFailed',
|
||||
{ error },
|
||||
{ error: errorDetail(error) },
|
||||
)
|
||||
} finally {
|
||||
setLocalImporting(false)
|
||||
|
||||
@@ -5,7 +5,7 @@ import { useTranslation } from 'react-i18next'
|
||||
import { BaseDialog, BaseLoadingOverlay } from '@/components/base'
|
||||
import { useVerge } from '@/hooks/use-verge'
|
||||
import { listWebDavBackup } from '@/services/cmds'
|
||||
import { showNotice } from '@/services/notice-service'
|
||||
import { errorDetail, showNotice } from '@/services/notice-service'
|
||||
import { buildWebdavSignature, setWebdavStatus } from '@/services/webdav-status'
|
||||
|
||||
import { BackupConfigViewer } from './backup-config-viewer'
|
||||
@@ -52,7 +52,7 @@ export const BackupWebdavDialog = ({
|
||||
setWebdavStatus(signature, 'failed')
|
||||
showNotice.error(
|
||||
'settings.modals.backup.messages.webdavRefreshFailed',
|
||||
{ error },
|
||||
{ error: errorDetail(error) },
|
||||
)
|
||||
} finally {
|
||||
handleLoading(false)
|
||||
|
||||
@@ -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