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
+5 -10
View File
@@ -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)
})
+45 -17
View File
@@ -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
+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,
}
+12
View File
@@ -36,6 +36,18 @@
"revalidationFailed": "تعذّر تحديث حالة التشغيل",
"sidecarFailed": "تعذّر المتابعة باستخدام Sidecar"
}
},
"sysproxyPrivilege": {
"title": "تعذّر ضبط وكيل النظام",
"message": "رفض macOS هذا التغيير لعدم كفاية الصلاحيات. بعد تثبيت خدمة Clash Verge ستتولى الخدمة تطبيق إعدادات الوكيل بصلاحيات المسؤول، ولن يظهر هذا التنبيه مجددًا.",
"serviceReadyMessage": "خدمة Clash Verge جاهزة، لكن النواة ما زالت تعمل كـ sidecar، ولهذا رُفض ضبط وكيل النظام. التبديل إلى وضع الخدمة يحل المشكلة دون إعادة تثبيت.",
"alternative": "بديل آخر: عطّل خيار طلب كلمة مرور المسؤول للوصول إلى الإعدادات على مستوى النظام من إعدادات النظام ← الخصوصية والأمان ← خيارات متقدمة.",
"later": "لاحقًا",
"installing": "جارٍ تثبيت خدمة النظام. قد يُطلب منك كلمة مرور المسؤول.",
"restarting": "تم تثبيت الخدمة. جارٍ إعادة تشغيل النواة من خلالها…",
"applying": "جارٍ تطبيق تغيير وكيل النظام…",
"tunTitle": "يحتاج وضع TUN إلى خدمة النظام",
"tunMessage": "يحتاج وضع TUN إلى خدمة نظام Clash Verge للتحكم في حركة الشبكة. بعد التثبيت سيتم تشغيل وضع TUN تلقائيًا."
}
},
"feedback": {
+13 -1
View File
@@ -37,11 +37,17 @@
},
"actions": {
"installService": "تثبيت الخدمة ",
"uninstallService": "Uninstall Service"
"uninstallService": "Uninstall Service",
"switchToServiceMode": "التبديل إلى وضع الخدمة"
},
"fields": {
"systemProxy": "وكيل النظام",
"tunMode": "وضع TUN"
},
"messages": {
"installedCheckProxy": "تم تثبيت الخدمة والنواة تعمل من خلالها. تحقّق من مفتاح وكيل النظام وأعد التغيير إن لم يُطبَّق.",
"installedCoreNotOnService": "تم تثبيت الخدمة، لكن النواة لا تعمل من خلالها. تحقّق من النواة ثم أعد المحاولة.",
"installedProxyRestored": "تم تثبيت الخدمة، وتعمل النواة من خلالها، وتم تطبيق تغيير وكيل النظام الخاص بك."
}
},
"externalController": {
@@ -649,6 +655,12 @@
"reinstallFailed": "تعذّر إعادة تثبيت الخدمة",
"repairFailed": "تعذّر إصلاح الخدمة",
"sidecarFailed": "تعذّر المتابعة باستخدام Sidecar"
},
"sysproxy": {
"privilegeRequired": "تعذّر ضبط وكيل النظام: رفض macOS التغيير لعدم كفاية الصلاحيات. ثبّت خدمة Clash Verge؛ وإن كنت مسؤولًا فيمكنك أيضًا إيقاف اشتراط كلمة سر المسؤول للإعدادات على مستوى النظام من الخيارات المتقدمة في إعدادات النظام ← الخصوصية والأمان.",
"directFallback": "تعذّر ضبط وكيل النظام؛ تمت إعادة حركة البيانات إلى اتصال مباشر.",
"guardStopped": "توقف حارس وكيل النظام بعد عدة إخفاقات متتالية. لم يعد وكيل النظام يُحفَظ تلقائيًا.",
"sidecarWhileServiceReady": "تعذّر ضبط وكيل النظام: خدمة Clash Verge جاهزة لكن النواة ما زالت تعمل بوضع Sidecar. أعد تشغيل النواة للتبديل إلى وضع الخدمة."
}
},
"notifications": {
+12
View File
@@ -36,6 +36,18 @@
"revalidationFailed": "Laufstatus konnte nicht aktualisiert werden",
"sidecarFailed": "Fortsetzung mit Sidecar fehlgeschlagen"
}
},
"sysproxyPrivilege": {
"title": "Systemproxy konnte nicht gesetzt werden",
"message": "macOS hat die Änderung mangels Berechtigungen abgelehnt. Nach Installation des Clash-Verge-Dienstes nimmt dieser die Proxy-Änderungen als Administrator vor, und dieser Hinweis erscheint nicht mehr.",
"serviceReadyMessage": "Der Clash-Verge-Dienst ist bereit, der Kern läuft aber noch als Sidecar — deshalb wurde das Setzen des Systemproxys abgelehnt. Ein Wechsel in den Dienstmodus behebt das, eine Neuinstallation ist nicht nötig.",
"alternative": "Alternativ: Deaktivieren Sie in den Systemeinstellungen → Datenschutz & Sicherheit → Erweitert die Option, die für systemweite Einstellungen ein Administratorkennwort verlangt.",
"later": "Später",
"installing": "Der Systemdienst wird installiert. Möglicherweise wird ein Administratorkennwort verlangt.",
"restarting": "Dienst installiert. Der Kern wird darüber neu gestartet…",
"applying": "Ihre Systemproxy-Änderung wird angewendet…",
"tunTitle": "Der TUN-Modus benötigt den Systemdienst",
"tunMessage": "Der TUN-Modus benötigt den Clash-Verge-Systemdienst, um den Netzwerkverkehr zu übernehmen. Nach der Installation wird der TUN-Modus für Sie eingeschaltet."
}
},
"feedback": {
+13 -1
View File
@@ -37,11 +37,17 @@
},
"actions": {
"installService": "Service installieren",
"uninstallService": "Dienst deinstallieren"
"uninstallService": "Dienst deinstallieren",
"switchToServiceMode": "In den Dienstmodus wechseln"
},
"fields": {
"systemProxy": "Systemproxy",
"tunMode": "Virtual Network Interface-Modus"
},
"messages": {
"installedCheckProxy": "Der Dienst ist installiert und der Kern läuft über ihn. Prüfen Sie den Systemproxy-Schalter und wiederholen Sie Ihre Änderung, falls sie nicht übernommen wurde.",
"installedCoreNotOnService": "Der Dienst ist installiert, der Kern läuft aber nicht über ihn. Prüfen Sie den Kern und versuchen Sie es erneut.",
"installedProxyRestored": "Der Dienst ist installiert, der Kern läuft darüber, und Ihre Systemproxy-Änderung wurde angewendet."
}
},
"externalController": {
@@ -649,6 +655,12 @@
"reinstallFailed": "Dienst konnte nicht neu installiert werden",
"repairFailed": "Dienst konnte nicht repariert werden",
"sidecarFailed": "Fortsetzung mit Sidecar fehlgeschlagen"
},
"sysproxy": {
"privilegeRequired": "Systemproxy kann nicht gesetzt werden: macOS hat die Änderung mangels Berechtigung abgelehnt. Installieren Sie den Clash-Verge-Dienst; als Administrator können Sie in den erweiterten Optionen unter Systemeinstellungen → Datenschutz & Sicherheit auch die Passwortpflicht für systemweite Einstellungen deaktivieren.",
"directFallback": "Systemproxy konnte nicht gesetzt werden; der Datenverkehr wurde auf eine direkte Verbindung zurückgesetzt.",
"guardStopped": "Der Systemproxy-Wächter wurde nach mehreren Fehlversuchen in Folge gestoppt. Der Systemproxy wird nicht mehr automatisch aufrechterhalten.",
"sidecarWhileServiceReady": "Der Systemproxy konnte nicht gesetzt werden: Der Clash-Verge-Dienst ist bereit, der Kern läuft aber noch als Sidecar. Starten Sie den Kern neu, um in den Dienstmodus zu wechseln."
}
},
"notifications": {
+12
View File
@@ -36,6 +36,18 @@
"revalidationFailed": "Failed to refresh the running state",
"sidecarFailed": "Failed to continue with Sidecar"
}
},
"sysproxyPrivilege": {
"title": "Could not set the system proxy",
"message": "macOS refused the change for lack of privileges. Installing the Clash Verge service lets it make proxy changes as an administrator, and this prompt will not come back.",
"serviceReadyMessage": "The Clash Verge service is ready, but the core is still running as a sidecar, which is why setting the system proxy was refused. Switching to service mode fixes it — no reinstall needed.",
"alternative": "Alternatively, turn off “require an administrator password to access system-wide settings” in System Settings → Privacy & Security → Advanced.",
"later": "Later",
"installing": "Installing the system service. This may ask for an administrator password.",
"restarting": "Service installed. Restarting the core through it…",
"applying": "Applying your system proxy change…",
"tunTitle": "TUN mode needs the system service",
"tunMessage": "TUN mode needs the Clash Verge system service to take over network traffic. Once it is installed, TUN mode will be turned on for you."
}
},
"feedback": {
+13 -1
View File
@@ -37,11 +37,17 @@
},
"actions": {
"installService": "Install Service",
"uninstallService": "Uninstall Service"
"uninstallService": "Uninstall Service",
"switchToServiceMode": "Switch to service mode"
},
"fields": {
"systemProxy": "System Proxy",
"tunMode": "Tun Mode"
},
"messages": {
"installedCheckProxy": "The service is installed and the core is running through it. Check the system proxy switch and make your change again if it did not take.",
"installedCoreNotOnService": "The service is installed, but the core is not running through it. Check the core and try again.",
"installedProxyRestored": "The service is installed, the core is running through it, and your system proxy change has been applied."
}
},
"externalController": {
@@ -649,6 +655,12 @@
"reinstallFailed": "Failed to reinstall the service",
"repairFailed": "Failed to repair the service",
"sidecarFailed": "Failed to continue with Sidecar"
},
"sysproxy": {
"privilegeRequired": "Cannot set the system proxy: macOS refused the change for lack of privileges. Install the Clash Verge service; an administrator can also turn off the administrator-password requirement for system-wide settings, in the advanced options of System Settings → Privacy & Security.",
"directFallback": "Failed to set the system proxy; traffic has been switched back to a direct connection.",
"guardStopped": "The system proxy guard stopped after failing several times running. The system proxy is no longer being kept in place.",
"sidecarWhileServiceReady": "The system proxy could not be set because the core is still running as a Sidecar, although the Clash Verge service is ready. Restart the core to switch to service mode."
}
},
"notifications": {
+12
View File
@@ -36,6 +36,18 @@
"revalidationFailed": "No se pudo actualizar el estado de ejecución",
"sidecarFailed": "No se pudo continuar con Sidecar"
}
},
"sysproxyPrivilege": {
"title": "No se pudo configurar el proxy del sistema",
"message": "macOS rechazó el cambio por falta de permisos. Al instalar el servicio de Clash Verge, este aplicará los cambios de proxy como administrador y este aviso no volverá a aparecer.",
"serviceReadyMessage": "El servicio de Clash Verge está listo, pero el núcleo sigue ejecutándose como sidecar, por eso se rechazó la configuración del proxy. Cambiar al modo servicio lo resuelve sin reinstalar.",
"alternative": "Otra opción: desactiva «requerir contraseña de administrador para acceder a los ajustes de todo el sistema» en Ajustes del Sistema → Privacidad y seguridad → Avanzado.",
"later": "Más tarde",
"installing": "Instalando el servicio del sistema. Puede pedir una contraseña de administrador.",
"restarting": "Servicio instalado. Reiniciando el núcleo a través de él…",
"applying": "Aplicando tu cambio de proxy del sistema…",
"tunTitle": "El modo TUN necesita el servicio del sistema",
"tunMessage": "El modo TUN necesita el servicio del sistema de Clash Verge para gestionar el tráfico de red. Una vez instalado, se activará el modo TUN por ti."
}
},
"feedback": {
+13 -1
View File
@@ -37,11 +37,17 @@
},
"actions": {
"installService": "Instalar servicio",
"uninstallService": "Desinstalar servicio"
"uninstallService": "Desinstalar servicio",
"switchToServiceMode": "Cambiar al modo de servicio"
},
"fields": {
"systemProxy": "Proxy del sistema",
"tunMode": "Modo de interfaz virtual (TUN)"
},
"messages": {
"installedCheckProxy": "El servicio está instalado y el núcleo se ejecuta a través de él. Revise el interruptor del proxy del sistema y repita el cambio si no se aplicó.",
"installedCoreNotOnService": "El servicio está instalado, pero el núcleo no se ejecuta a través de él. Revise el núcleo e inténtelo de nuevo.",
"installedProxyRestored": "El servicio está instalado, el núcleo se ejecuta a través de él y se ha aplicado tu cambio de proxy del sistema."
}
},
"externalController": {
@@ -649,6 +655,12 @@
"reinstallFailed": "No se pudo reinstalar el servicio",
"repairFailed": "No se pudo reparar el servicio",
"sidecarFailed": "No se pudo continuar con Sidecar"
},
"sysproxy": {
"privilegeRequired": "No se puede establecer el proxy del sistema: macOS rechazó el cambio por falta de permisos. Instale el servicio de Clash Verge; si es administrador, también puede desactivar la exigencia de contraseña de administrador para los ajustes de todo el sistema en las opciones avanzadas de Ajustes del Sistema → Privacidad y seguridad.",
"directFallback": "No se pudo establecer el proxy del sistema; el tráfico volvió a una conexión directa.",
"guardStopped": "El guardián del proxy del sistema se detuvo tras varios fallos seguidos. El proxy del sistema ya no se mantiene automáticamente.",
"sidecarWhileServiceReady": "No se pudo establecer el proxy del sistema: el servicio de Clash Verge está listo, pero el núcleo sigue ejecutándose como Sidecar. Reinicie el núcleo para cambiar al modo de servicio."
}
},
"notifications": {
+12
View File
@@ -36,6 +36,18 @@
"revalidationFailed": "به‌روزرسانی وضعیت اجرا ناموفق بود",
"sidecarFailed": "ادامه با Sidecar ناموفق بود"
}
},
"sysproxyPrivilege": {
"title": "تنظیم پروکسی سیستم ممکن نشد",
"message": "macOS این تغییر را به دلیل نبود دسترسی رد کرد. با نصب سرویس Clash Verge، تغییرات پروکسی توسط سرویس و با دسترسی مدیر انجام می‌شود و این پیام دیگر نمایش داده نمی‌شود.",
"serviceReadyMessage": "سرویس Clash Verge آماده است، اما هسته هنوز به‌صورت sidecar اجرا می‌شود و به همین دلیل تنظیم پروکسی رد شد. تغییر به حالت سرویس آن را حل می‌کند و نیازی به نصب مجدد نیست.",
"alternative": "راه دیگر: در تنظیمات سیستم ← حریم خصوصی و امنیت ← پیشرفته، گزینهٔ نیاز به گذرواژهٔ مدیر برای تنظیمات سراسری را خاموش کنید.",
"later": "بعداً",
"installing": "در حال نصب سرویس سیستم. ممکن است گذرواژهٔ مدیر خواسته شود.",
"restarting": "سرویس نصب شد. هسته از طریق آن راه‌اندازی مجدد می‌شود…",
"applying": "در حال اعمال تغییر پروکسی سیستم…",
"tunTitle": "حالت TUN به سرویس سیستم نیاز دارد",
"tunMessage": "حالت TUN برای در دست گرفتن ترافیک شبکه به سرویس سیستم Clash Verge نیاز دارد. پس از نصب، حالت TUN برای شما روشن می‌شود."
}
},
"feedback": {
+13 -1
View File
@@ -37,11 +37,17 @@
},
"actions": {
"installService": "نصب سرویس",
"uninstallService": "حذف سرویس"
"uninstallService": "حذف سرویس",
"switchToServiceMode": "رفتن به حالت سرویس"
},
"fields": {
"systemProxy": "پراکسی سیستم",
"tunMode": "Tun (کارت شبکه مجازی)"
},
"messages": {
"installedCheckProxy": "سرویس نصب شد و هسته از طریق آن اجرا می‌شود. کلید پراکسی سیستم را بررسی کنید و اگر تغییر شما اعمال نشده، دوباره انجامش دهید.",
"installedCoreNotOnService": "سرویس نصب شد، اما هسته از طریق آن اجرا نمی‌شود. وضعیت هسته را بررسی کنید و دوباره تلاش کنید.",
"installedProxyRestored": "سرویس نصب شد، هسته از طریق آن اجرا می‌شود و تغییر پروکسی سیستم شما اعمال شد."
}
},
"externalController": {
@@ -649,6 +655,12 @@
"reinstallFailed": "نصب مجدد سرویس ناموفق بود",
"repairFailed": "تعمیر سرویس ناموفق بود",
"sidecarFailed": "ادامه با Sidecar ناموفق بود"
},
"sysproxy": {
"privilegeRequired": "تنظیم پراکسی سیستم ممکن نیست: macOS به دلیل نداشتن دسترسی، این تغییر را رد کرد. سرویس Clash Verge را نصب کنید؛ اگر مدیر هستید می‌توانید در گزینه‌های پیشرفتهٔ تنظیمات سیستم ← حریم خصوصی و امنیت، الزام رمز مدیر برای تنظیمات سراسری سیستم را نیز خاموش کنید.",
"directFallback": "تنظیم پراکسی سیستم ناموفق بود؛ ترافیک به اتصال مستقیم بازگردانده شد.",
"guardStopped": "نگهبان پراکسی سیستم پس از چند شکست پیاپی متوقف شد. پراکسی سیستم دیگر به‌طور خودکار نگه داشته نمی‌شود.",
"sidecarWhileServiceReady": "تنظیم پراکسی سیستم ممکن نشد: سرویس Clash Verge آماده است اما هسته هنوز به‌صورت Sidecar اجرا می‌شود. برای رفتن به حالت سرویس، هسته را دوباره راه‌اندازی کنید."
}
},
"notifications": {
+12
View File
@@ -36,6 +36,18 @@
"revalidationFailed": "Gagal menyegarkan status berjalan",
"sidecarFailed": "Gagal melanjutkan dengan Sidecar"
}
},
"sysproxyPrivilege": {
"title": "Tidak dapat mengatur proxy sistem",
"message": "macOS menolak perubahan ini karena izin tidak cukup. Setelah layanan Clash Verge dipasang, layanan akan menerapkan pengaturan proxy sebagai administrator dan pesan ini tidak akan muncul lagi.",
"serviceReadyMessage": "Layanan Clash Verge sudah siap, tetapi core masih berjalan sebagai sidecar sehingga pengaturan proxy sistem ditolak. Beralih ke mode layanan mengatasinya tanpa pemasangan ulang.",
"alternative": "Alternatif: matikan opsi yang mewajibkan kata sandi administrator untuk mengakses pengaturan seluruh sistem di Pengaturan Sistem → Privasi & Keamanan → Lanjutan.",
"later": "Nanti",
"installing": "Memasang layanan sistem. Kata sandi administrator mungkin diminta.",
"restarting": "Layanan terpasang. Memulai ulang core melaluinya…",
"applying": "Menerapkan perubahan proxy sistem Anda…",
"tunTitle": "Mode TUN memerlukan layanan sistem",
"tunMessage": "Mode TUN memerlukan layanan sistem Clash Verge untuk mengambil alih lalu lintas jaringan. Setelah terpasang, mode TUN akan diaktifkan untuk Anda."
}
},
"feedback": {
+13 -1
View File
@@ -37,11 +37,17 @@
},
"actions": {
"installService": "Instal Layanan",
"uninstallService": "Uninstall Service"
"uninstallService": "Uninstall Service",
"switchToServiceMode": "Beralih ke mode layanan"
},
"fields": {
"systemProxy": "Proksi Sistem",
"tunMode": "Mode Tun (NIC Virtual)"
},
"messages": {
"installedCheckProxy": "Layanan terpasang dan inti berjalan melaluinya. Periksa sakelar proxy sistem dan ulangi perubahan Anda jika belum diterapkan.",
"installedCoreNotOnService": "Layanan terpasang, tetapi inti tidak berjalan melaluinya. Periksa inti lalu coba lagi.",
"installedProxyRestored": "Layanan telah dipasang, core berjalan melaluinya, dan perubahan proxy sistem Anda telah diterapkan."
}
},
"externalController": {
@@ -649,6 +655,12 @@
"reinstallFailed": "Gagal memasang ulang layanan",
"repairFailed": "Gagal memperbaiki layanan",
"sidecarFailed": "Gagal melanjutkan dengan Sidecar"
},
"sysproxy": {
"privilegeRequired": "Tidak dapat mengatur proxy sistem: macOS menolak perubahan ini karena hak akses tidak mencukupi. Pasang layanan Clash Verge; jika Anda administrator, Anda juga dapat mematikan keharusan kata sandi administrator untuk pengaturan seluruh sistem di opsi lanjutan Pengaturan Sistem → Privasi & Keamanan.",
"directFallback": "Gagal mengatur proxy sistem; lalu lintas dikembalikan ke koneksi langsung.",
"guardStopped": "Penjaga proxy sistem berhenti setelah gagal beberapa kali berturut-turut. Proxy sistem tidak lagi dipertahankan secara otomatis.",
"sidecarWhileServiceReady": "Proxy sistem tidak dapat diatur: layanan Clash Verge sudah siap, tetapi inti masih berjalan sebagai Sidecar. Mulai ulang inti untuk beralih ke mode layanan."
}
},
"notifications": {
+12
View File
@@ -36,6 +36,18 @@
"revalidationFailed": "実行状態の更新に失敗しました",
"sidecarFailed": "Sidecar での続行に失敗しました"
}
},
"sysproxyPrivilege": {
"title": "システムプロキシを設定できません",
"message": "権限が不足しているため、macOS がこの変更を拒否しました。Clash Verge サービスをインストールすると、サービスが管理者としてプロキシを設定するようになり、この通知は表示されなくなります。",
"serviceReadyMessage": "Clash Verge サービスは準備できていますが、コアがまだ sidecar として動作しているため、システムプロキシの設定が拒否されました。サービスモードに切り替えれば、再インストールせずに解決します。",
"alternative": "別の方法として、システム設定 → プライバシーとセキュリティ → 詳細で、システム全体の設定に管理者パスワードを要求するオプションをオフにしてください。",
"later": "後で",
"installing": "システムサービスをインストールしています。管理者パスワードを求められる場合があります。",
"restarting": "サービスをインストールしました。サービス経由でコアを再起動しています…",
"applying": "システムプロキシの変更を適用しています…",
"tunTitle": "TUN モードにはシステムサービスが必要です",
"tunMessage": "TUN モードがネットワークトラフィックを処理するには Clash Verge システムサービスが必要です。インストールが完了すると TUN モードが自動で有効になります。"
}
},
"feedback": {
+13 -1
View File
@@ -37,11 +37,17 @@
},
"actions": {
"installService": "サービスをインストール",
"uninstallService": "サービスのアンインストール"
"uninstallService": "サービスのアンインストール",
"switchToServiceMode": "サービスモードに切り替え"
},
"fields": {
"systemProxy": "システムプロキシ",
"tunMode": "仮想ネットワークカードモード"
},
"messages": {
"installedCheckProxy": "サービスをインストールし、コアはサービス経由で動作しています。システムプロキシのスイッチを確認し、先ほどの変更が反映されていなければやり直してください。",
"installedCoreNotOnService": "サービスはインストールされましたが、コアはサービス経由で動作していません。コアの状態を確認してからやり直してください。",
"installedProxyRestored": "サービスがインストールされ、コアはサービス経由で動作しており、システムプロキシの変更が適用されました。"
}
},
"externalController": {
@@ -649,6 +655,12 @@
"reinstallFailed": "サービスの再インストールに失敗しました",
"repairFailed": "サービスの修復に失敗しました",
"sidecarFailed": "Sidecar での続行に失敗しました"
},
"sysproxy": {
"privilegeRequired": "システムプロキシを設定できません: 権限が不足しているため macOS が変更を拒否しました。Clash Verge サービスをインストールしてください。管理者であれば、システム設定 → プライバシーとセキュリティの詳細オプションで、システム全体の設定に管理者パスワードを要求する設定をオフにすることもできます。",
"directFallback": "システムプロキシの設定に失敗したため、直接接続に戻しました。",
"guardStopped": "システムプロキシガードが連続して失敗したため停止しました。システムプロキシは自動的に維持されなくなりました。",
"sidecarWhileServiceReady": "システムプロキシを設定できませんでした: Clash Verge サービスは準備できていますが、コアはまだ Sidecar で動作しています。コアを再起動するとサービスモードに切り替わります。"
}
},
"notifications": {
+12
View File
@@ -36,6 +36,18 @@
"revalidationFailed": "실행 상태를 새로 고치지 못했습니다",
"sidecarFailed": "Sidecar로 계속하지 못했습니다"
}
},
"sysproxyPrivilege": {
"title": "시스템 프록시를 설정할 수 없음",
"message": "macOS가 권한 부족을 이유로 이 변경을 거부했습니다. Clash Verge 서비스를 설치하면 서비스가 관리자 권한으로 프록시를 설정하며, 이 알림은 다시 나타나지 않습니다.",
"serviceReadyMessage": "Clash Verge 서비스는 준비되었지만 코어가 아직 sidecar로 실행 중이어서 시스템 프록시 설정이 거부되었습니다. 서비스 모드로 전환하면 재설치 없이 해결됩니다.",
"alternative": "다른 방법: 시스템 설정 → 개인정보 보호 및 보안 → 고급에서 시스템 전체 설정에 관리자 암호를 요구하는 옵션을 끄십시오.",
"later": "나중에",
"installing": "시스템 서비스를 설치하는 중입니다. 관리자 암호를 요청할 수 있습니다.",
"restarting": "서비스가 설치되었습니다. 서비스를 통해 코어를 다시 시작하는 중…",
"applying": "시스템 프록시 변경 사항을 적용하는 중…",
"tunTitle": "TUN 모드에는 시스템 서비스가 필요합니다",
"tunMessage": "TUN 모드가 네트워크 트래픽을 처리하려면 Clash Verge 시스템 서비스가 필요합니다. 설치가 끝나면 TUN 모드가 자동으로 켜집니다."
}
},
"feedback": {
+13 -1
View File
@@ -37,11 +37,17 @@
},
"actions": {
"installService": "서비스 설치",
"uninstallService": "서비스 제거"
"uninstallService": "서비스 제거",
"switchToServiceMode": "서비스 모드로 전환"
},
"fields": {
"systemProxy": "시스템 프록시",
"tunMode": "TUN 모드"
},
"messages": {
"installedCheckProxy": "서비스가 설치되었고 코어가 서비스를 통해 실행 중입니다. 시스템 프록시 스위치를 확인하고, 방금 한 변경이 적용되지 않았다면 다시 시도하십시오.",
"installedCoreNotOnService": "서비스는 설치되었지만 코어가 서비스를 통해 실행되고 있지 않습니다. 코어 상태를 확인한 뒤 다시 시도하십시오.",
"installedProxyRestored": "서비스가 설치되었고 코어가 서비스를 통해 실행되며, 시스템 프록시 변경 사항이 적용되었습니다."
}
},
"externalController": {
@@ -649,6 +655,12 @@
"reinstallFailed": "서비스를 다시 설치하지 못했습니다",
"repairFailed": "서비스를 복구하지 못했습니다",
"sidecarFailed": "Sidecar로 계속하지 못했습니다"
},
"sysproxy": {
"privilegeRequired": "시스템 프록시를 설정할 수 없습니다: 권한이 부족하여 macOS가 변경을 거부했습니다. Clash Verge 서비스를 설치하십시오. 관리자라면 시스템 설정 → 개인 정보 보호 및 보안의 고급 옵션에서, 시스템 전체 설정에 관리자 암호를 요구하는 설정을 끌 수도 있습니다.",
"directFallback": "시스템 프록시 설정에 실패하여 직접 연결로 되돌렸습니다.",
"guardStopped": "시스템 프록시 가드가 연속으로 실패하여 중지되었습니다. 시스템 프록시가 더 이상 자동으로 유지되지 않습니다.",
"sidecarWhileServiceReady": "시스템 프록시를 설정하지 못했습니다: Clash Verge 서비스는 준비되었지만 코어가 아직 Sidecar로 실행 중입니다. 코어를 재시작하면 서비스 모드로 전환됩니다."
}
},
"notifications": {
+12
View File
@@ -36,6 +36,18 @@
"revalidationFailed": "Не удалось обновить состояние выполнения",
"sidecarFailed": "Не удалось продолжить в режиме Sidecar"
}
},
"sysproxyPrivilege": {
"title": "Не удалось настроить системный прокси",
"message": "macOS отклонила изменение из-за нехватки прав. После установки службы Clash Verge настройки прокси будет применять служба с правами администратора, и это сообщение больше не появится.",
"serviceReadyMessage": "Служба Clash Verge готова, но ядро всё ещё работает как sidecar, поэтому в настройке системного прокси отказано. Переключение в режим службы решает проблему без переустановки.",
"alternative": "Другой вариант: отключите «требовать пароль администратора для доступа к общесистемным настройкам» в Системных настройках → Конфиденциальность и безопасность → Дополнительно.",
"later": "Позже",
"installing": "Устанавливается системная служба. Может потребоваться пароль администратора.",
"restarting": "Служба установлена. Ядро перезапускается через неё…",
"applying": "Применяется изменение системного прокси…",
"tunTitle": "Для режима TUN нужна системная служба",
"tunMessage": "Режиму TUN нужна системная служба Clash Verge, чтобы взять сетевой трафик на себя. После установки режим TUN будет включён автоматически."
}
},
"feedback": {
+13 -1
View File
@@ -37,11 +37,17 @@
},
"actions": {
"installService": "Установить службу",
"uninstallService": "Удалить службу"
"uninstallService": "Удалить службу",
"switchToServiceMode": "Переключиться в режим службы"
},
"fields": {
"systemProxy": "Системный прокси",
"tunMode": "Режим TUN"
},
"messages": {
"installedCheckProxy": "Служба установлена, ядро работает через неё. Проверьте переключатель системного прокси и повторите изменение, если оно не применилось.",
"installedCoreNotOnService": "Служба установлена, но ядро работает не через неё. Проверьте состояние ядра и повторите попытку.",
"installedProxyRestored": "Служба установлена, ядро работает через неё, и ваше изменение системного прокси применено."
}
},
"externalController": {
@@ -649,6 +655,12 @@
"reinstallFailed": "Не удалось переустановить службу",
"repairFailed": "Не удалось восстановить службу",
"sidecarFailed": "Не удалось продолжить в режиме Sidecar"
},
"sysproxy": {
"privilegeRequired": "Не удалось настроить системный прокси: macOS отклонил изменение из-за нехватки прав. Установите службу Clash Verge; администратор также может отключить требование пароля администратора для общесистемных настроек в дополнительных параметрах раздела «Системные настройки → Конфиденциальность и безопасность».",
"directFallback": "Не удалось настроить системный прокси; трафик возвращён к прямому подключению.",
"guardStopped": "Страж системного прокси остановился после нескольких неудач подряд. Системный прокси больше не поддерживается автоматически.",
"sidecarWhileServiceReady": "Не удалось настроить системный прокси: служба Clash Verge готова, но ядро всё ещё работает в режиме Sidecar. Перезапустите ядро, чтобы переключиться в режим службы."
}
},
"notifications": {
+12
View File
@@ -36,6 +36,18 @@
"revalidationFailed": "Çalışma durumu yenilenemedi",
"sidecarFailed": "Sidecar ile devam edilemedi"
}
},
"sysproxyPrivilege": {
"title": "Sistem proxy'si ayarlanamadı",
"message": "macOS bu değişikliği yetersiz yetki nedeniyle reddetti. Clash Verge hizmeti kurulduktan sonra proxy ayarlarını hizmet yönetici olarak uygular ve bu uyarı bir daha görünmez.",
"serviceReadyMessage": "Clash Verge hizmeti hazır, ancak çekirdek hâlâ sidecar olarak çalıştığından sistem proxy'si ayarlanamadı. Hizmet moduna geçmek sorunu yeniden kurulum gerekmeden çözer.",
"alternative": "Alternatif olarak Sistem Ayarları → Gizlilik ve Güvenlik → Gelişmiş bölümünde sistem genelindeki ayarlar için yönetici parolası isteyen seçeneği kapatın.",
"later": "Daha sonra",
"installing": "Sistem hizmeti kuruluyor. Yönetici parolası istenebilir.",
"restarting": "Hizmet kuruldu. Çekirdek onun üzerinden yeniden başlatılıyor…",
"applying": "Sistem proxy değişikliğiniz uygulanıyor…",
"tunTitle": "TUN modu sistem hizmetine ihtiyaç duyar",
"tunMessage": "TUN modunun ağ trafiğini üstlenebilmesi için Clash Verge sistem hizmeti gerekir. Kurulum tamamlandığında TUN modu sizin için açılacaktır."
}
},
"feedback": {
+13 -1
View File
@@ -37,11 +37,17 @@
},
"actions": {
"installService": "Hizmeti Kur",
"uninstallService": "Uninstall Service"
"uninstallService": "Uninstall Service",
"switchToServiceMode": "Hizmet moduna geç"
},
"fields": {
"systemProxy": "Sistem Vekil'i",
"tunMode": "Tun Modu"
},
"messages": {
"installedCheckProxy": "Hizmet kuruldu ve çekirdek onun üzerinden çalışıyor. Sistem vekil sunucusu anahtarını denetleyin; değişikliğiniz uygulanmadıysa yeniden yapın.",
"installedCoreNotOnService": "Hizmet kuruldu ancak çekirdek onun üzerinden çalışmıyor. Çekirdeği denetleyip yeniden deneyin.",
"installedProxyRestored": "Hizmet kuruldu, çekirdek onun üzerinden çalışıyor ve sistem proxy değişikliğiniz uygulandı."
}
},
"externalController": {
@@ -649,6 +655,12 @@
"reinstallFailed": "Hizmet yeniden kurulamadı",
"repairFailed": "Hizmet onarılamadı",
"sidecarFailed": "Sidecar ile devam edilemedi"
},
"sysproxy": {
"privilegeRequired": "Sistem vekil sunucusu ayarlanamıyor: macOS yetki yetersizliği nedeniyle değişikliği reddetti. Clash Verge hizmetini kurun; yöneticiyseniz Sistem Ayarları → Gizlilik ve Güvenlik bölümündeki gelişmiş seçeneklerden, sistem genelindeki ayarlar için yönetici parolası zorunluluğunu da kapatabilirsiniz.",
"directFallback": "Sistem vekil sunucusu ayarlanamadı; trafik doğrudan bağlantıya geri döndürüldü.",
"guardStopped": "Sistem vekil sunucusu koruması art arda birkaç başarısızlıktan sonra durdu. Sistem vekil sunucusu artık otomatik olarak korunmuyor.",
"sidecarWhileServiceReady": "Sistem vekil sunucusu ayarlanamadı: Clash Verge hizmeti hazır ancak çekirdek hâlâ Sidecar olarak çalışıyor. Hizmet moduna geçmek için çekirdeği yeniden başlatın."
}
},
"notifications": {
+12
View File
@@ -36,6 +36,18 @@
"revalidationFailed": "Эшләү халәтен яңартып булмады",
"sidecarFailed": "Sidecar белән дәвам итеп булмады"
}
},
"sysproxyPrivilege": {
"title": "Система прокси көйләнмәде",
"message": "macOS бу үзгәрешне хокуклар җитмәү сәбәпле кире какты. Clash Verge хезмәтен урнаштыргач, прокси көйләүләрен хезмәт администратор буларак башкара, һәм бу хәбәр кабат күренмәс.",
"serviceReadyMessage": "Clash Verge хезмәте әзер, ләкин үзәк әле дә sidecar буларак эшли, шуңа күрә система проксиен көйләү кире кагылды. Хезмәт режимына күчү моны яңадан урнаштырмыйча хәл итә.",
"alternative": "Башка юл: Система көйләүләре → Хосусыйлык һәм куркынычсызлык → Өстәмә бүлегендә система күләмендәге көйләүләр өчен администратор паролен сорау опциясен сүндерегез.",
"later": "Соңрак",
"installing": "Система хезмәте урнаштырыла. Администратор паролен сорарга мөмкин.",
"restarting": "Хезмәт урнаштырылды. Үзәк аның аша яңадан җибәрелә…",
"applying": "Система прокси үзгәреше кулланыла…",
"tunTitle": "TUN режимына система хезмәте кирәк",
"tunMessage": "TUN режимына челтәр трафигын үз өстенә алу өчен Clash Verge система хезмәте кирәк. Урнаштырылгач, TUN режимы сезнең өчен кабызылачак."
}
},
"feedback": {
+13 -1
View File
@@ -37,11 +37,17 @@
},
"actions": {
"installService": "Хезмәтне урнаштыру",
"uninstallService": "Uninstall Service"
"uninstallService": "Uninstall Service",
"switchToServiceMode": "Хезмәт режимына күчү"
},
"fields": {
"systemProxy": "Системалы прокси",
"tunMode": "Tun режимы (виртуаль челтәр адаптеры)"
},
"messages": {
"installedCheckProxy": "Хезмәт урнаштырылды, ядро хезмәт аша эшли. Система проксие тоткычын тикшерегез; үзгәреш эшләмәгән булса, кабатлагыз.",
"installedCoreNotOnService": "Хезмәт урнаштырылды, әмма ядро хезмәт аша эшләми. Ядро халәтен тикшереп кабат карагыз.",
"installedProxyRestored": "Хезмәт урнаштырылды, үзәк аның аша эшли, һәм система прокси үзгәрешегез кулланылды."
}
},
"externalController": {
@@ -649,6 +655,12 @@
"reinstallFailed": "Хезмәтне яңадан урнаштырып булмады",
"repairFailed": "Хезмәтне төзәтеп булмады",
"sidecarFailed": "Sidecar белән дәвам итеп булмады"
},
"sysproxy": {
"privilegeRequired": "Система проксиен көйләп булмый: хокуклар җитмәгәнгә күрә macOS бу үзгәрешне кире какты. Clash Verge хезмәтен урнаштырыгыз; әгәр сез администратор булсагыз, Система көйләнмәләре → Шәхсилек вә иминлек бүлегенең өстәмә параметрларында, система дәрәҗәсендәге көйләнмәләр өчен администратор паролен таләп итүне сүндерә аласыз.",
"directFallback": "Система проксиен көйләү уңышсыз булды; трафик туры тоташуга кайтарылды.",
"guardStopped": "Система проксие сакчысы берничә тапкыр рәттән уңышсыз булганнан соң туктады. Система проксие бүтән автоматик рәвештә саклап торылмый.",
"sidecarWhileServiceReady": "Система проксиен көйләп булмады: Clash Verge хезмәте әзер, әмма ядро һаман Sidecar буларак эшли. Хезмәт режимына күчәр өчен ядрону яңадан эшләтегез."
}
},
"notifications": {
+12
View File
@@ -36,6 +36,18 @@
"revalidationFailed": "刷新运行状态失败",
"sidecarFailed": "继续使用 Sidecar 失败"
}
},
"sysproxyPrivilege": {
"title": "无法设置系统代理",
"message": "macOS 以权限不足为由拒绝了这次修改。安装 Clash Verge 系统服务后,代理设置将由服务以管理员身份完成,之后不会再出现这个提示。",
"serviceReadyMessage": "Clash Verge 系统服务已就绪,但内核仍以 Sidecar 运行,因此设置系统代理时被拒绝。切换到服务模式即可解决,无需重新安装。",
"alternative": "另一种办法:在系统设置 → 隐私与安全性 → 高级中,关闭「访问系统范围设置需要管理员密码」。",
"later": "稍后再说",
"installing": "正在安装系统服务,可能会请求管理员密码,请稍候……",
"restarting": "服务已安装,正在通过服务重启内核……",
"applying": "正在重新应用系统代理……",
"tunTitle": "TUN 模式需要系统服务",
"tunMessage": "TUN 模式需要 Clash Verge 系统服务才能接管网络流量。安装完成后会自动为你开启 TUN 模式。"
}
},
"feedback": {
+13 -1
View File
@@ -37,11 +37,17 @@
},
"actions": {
"installService": "安装服务",
"uninstallService": "卸载服务"
"uninstallService": "卸载服务",
"switchToServiceMode": "切换到服务模式"
},
"fields": {
"systemProxy": "系统代理",
"tunMode": "虚拟网卡模式"
},
"messages": {
"installedCheckProxy": "服务已安装,内核已通过服务运行。请检查系统代理开关,若刚才的改动未生效请重新操作一次。",
"installedCoreNotOnService": "服务已安装,但内核未通过服务运行。请检查内核状态后重试。",
"installedProxyRestored": "服务已安装,内核已通过服务运行,刚才的系统代理改动已重新应用。"
}
},
"externalController": {
@@ -649,6 +655,12 @@
"reinstallFailed": "重新安装服务失败",
"repairFailed": "修复服务失败",
"sidecarFailed": "继续使用 Sidecar 失败"
},
"sysproxy": {
"privilegeRequired": "无法设置系统代理:macOS 以权限不足为由拒绝了这次修改。请安装 Clash Verge 服务;管理员也可以在系统设置 → 隐私与安全性的高级选项中,关闭访问系统范围设置需要管理员密码的要求。",
"directFallback": "系统代理设置失败,已回退为直连。",
"guardStopped": "系统代理守卫连续多次失败后已停止,系统代理不再被自动维持。",
"sidecarWhileServiceReady": "系统代理设置失败:Clash Verge 服务已就绪,但内核仍以 Sidecar 运行。重启内核即可切换到服务模式。"
}
},
"notifications": {
+12
View File
@@ -36,6 +36,18 @@
"revalidationFailed": "重新整理執行狀態失敗",
"sidecarFailed": "繼續使用 Sidecar 失敗"
}
},
"sysproxyPrivilege": {
"title": "無法設定系統代理",
"message": "macOS 以權限不足為由拒絕了這次修改。安裝 Clash Verge 系統服務後,代理設定將由服務以管理員身分完成,之後不會再出現這個提示。",
"serviceReadyMessage": "Clash Verge 系統服務已就緒,但核心仍以 Sidecar 執行,因此設定系統代理時被拒絕。切換到服務模式即可解決,無需重新安裝。",
"alternative": "另一種辦法:在系統設定 → 隱私權與安全性 → 進階中,關閉「存取系統範圍設定需要管理員密碼」。",
"later": "稍後再說",
"installing": "正在安裝系統服務,可能會要求管理員密碼,請稍候……",
"restarting": "服務已安裝,正在透過服務重新啟動核心……",
"applying": "正在重新套用系統代理……",
"tunTitle": "TUN 模式需要系統服務",
"tunMessage": "TUN 模式需要 Clash Verge 系統服務才能接管網路流量。安裝完成後會自動為你開啟 TUN 模式。"
}
},
"feedback": {
+13 -1
View File
@@ -37,11 +37,17 @@
},
"actions": {
"installService": "安裝服務",
"uninstallService": "解除安裝服務"
"uninstallService": "解除安裝服務",
"switchToServiceMode": "切換到服務模式"
},
"fields": {
"systemProxy": "系統代理",
"tunMode": "虛擬網路介面卡模式"
},
"messages": {
"installedCheckProxy": "服務已安裝,內核已透過服務執行。請檢查系統代理開關,若剛才的變更未生效請重新操作一次。",
"installedCoreNotOnService": "服務已安裝,但內核未透過服務執行。請檢查內核狀態後重試。",
"installedProxyRestored": "服務已安裝,核心已透過服務執行,剛才的系統代理變更已重新套用。"
}
},
"externalController": {
@@ -649,6 +655,12 @@
"reinstallFailed": "重新安裝服務失敗",
"repairFailed": "修復服務失敗",
"sidecarFailed": "繼續使用 Sidecar 失敗"
},
"sysproxy": {
"privilegeRequired": "無法設定系統代理:macOS 以權限不足為由拒絕了這次修改。請安裝 Clash Verge 服務;管理者也可以在系統設定 → 隱私權與安全性的進階選項中,關閉存取系統層級設定需要管理者密碼的要求。",
"directFallback": "系統代理設定失敗,已回退為直連。",
"guardStopped": "系統代理守衛連續多次失敗後已停止,系統代理不再被自動維持。",
"sidecarWhileServiceReady": "系統代理設定失敗:Clash Verge 服務已就緒,但內核仍以 Sidecar 執行。重新啟動內核即可切換到服務模式。"
}
},
"notifications": {
+4
View File
@@ -37,6 +37,7 @@ import { LayoutItem } from '@/components/layout/layout-item'
import { LayoutTraffic } from '@/components/layout/layout-traffic'
import { NoticeManager } from '@/components/layout/notice-manager'
import { ServiceMigrationDialog } from '@/components/layout/service-migration-dialog'
import { SysproxyPrivilegeDialog } from '@/components/layout/sysproxy-privilege-dialog'
import { UpdateButton } from '@/components/layout/update-button'
import {
WindowControls,
@@ -53,6 +54,7 @@ import {
useLayoutEvents,
useLoadingOverlay,
useNavMenuOrder,
usePendingFailures,
} from './_layout/hooks'
import { handleNoticeMessage } from './_layout/utils'
import { navItems } from './_navigation'
@@ -250,6 +252,7 @@ const Layout = () => {
)
useLayoutEvents(handleNotice)
usePendingFailures()
useEffect(() => {
if (language) {
@@ -280,6 +283,7 @@ const Layout = () => {
{/* 左侧底部窗口控制按钮 */}
<NoticeManager position={verge?.notice_position} />
<ServiceMigrationDialog />
<SysproxyPrivilegeDialog />
<div
style={{
animation: 'fadeIn 0.5s',
+1
View File
@@ -1,4 +1,5 @@
export { useLayoutEvents } from './use-layout-events'
export { usePendingFailures, useDialogFailure } from './use-pending-failures'
export { useLoadingOverlay } from './use-loading-overlay'
export { useNavMenuOrder } from './use-nav-menu-order'
export { useCustomTheme } from './use-custom-theme'
@@ -0,0 +1,228 @@
// @vitest-environment jsdom
import { act, cleanup, renderHook, waitFor } from '@testing-library/react'
import { afterEach, beforeEach, expect, it, vi } from 'vitest'
import type { PendingFailure } from '@/services/cmds'
import { getSnapshotNotices, hideNotice } from '@/services/notice-service'
import { useDialogFailure, usePendingFailures } from './use-pending-failures'
const getPendingFailures = vi.hoisted(() => vi.fn())
const onFocusChanged = vi.hoisted(() => vi.fn())
const isVisible = vi.hoisted(() => vi.fn())
const isMinimized = vi.hoisted(() => vi.fn())
vi.mock('@/services/cmds', () => ({ getPendingFailures }))
vi.mock('@tauri-apps/api/window', () => ({
getCurrentWindow: () => ({ onFocusChanged, isVisible, isMinimized }),
}))
let table: PendingFailure[] = []
let onSubscribed: (() => void) | undefined
let onTableChanged: (() => void) | undefined
let focusListener: ((event: { payload: boolean }) => void) | undefined
vi.mock('@/services/events', () => ({
subscribeVergeEvents: (
handlers: Record<string, () => void>,
subscribed?: () => void,
) => {
onTableChanged = handlers['verge://pending-failures-changed']
onSubscribed = subscribed
return () => {}
},
}))
const failure = (sequence: number, detail: string): PendingFailure => ({
code: 'SYSPROXY_GUARD_STOPPED',
detail,
operation: 'systemProxyGuard',
sequence,
})
const dialogFailure = (sequence: number): PendingFailure => ({
code: 'SYSPROXY_PRIVILEGE_REQUIRED',
detail: 'refused',
operation: 'systemProxyEnable',
sequence,
})
const shownDetails = () =>
getSnapshotNotices().map((notice) => notice.i18n?.params?.message)
beforeEach(() => {
getPendingFailures.mockClear()
onFocusChanged.mockClear()
isVisible.mockReset()
isVisible.mockResolvedValue(true)
isMinimized.mockReset()
isMinimized.mockResolvedValue(false)
table = []
onSubscribed = undefined
onTableChanged = undefined
focusListener = undefined
getPendingFailures.mockImplementation(() => Promise.resolve(table))
onFocusChanged.mockImplementation(
(listener: (event: { payload: boolean }) => void) => {
focusListener = listener
return Promise.resolve(() => {})
},
)
})
afterEach(() => {
cleanup()
getSnapshotNotices().forEach((notice) => hideNotice(notice.id))
})
it('shows a failure that was recorded before the listeners were live', async () => {
table = [failure(1, 'refused')]
renderHook(() => usePendingFailures())
onSubscribed?.()
await waitFor(() => expect(shownDetails()).toEqual(['refused']))
})
it('shows a failure recorded after the window was already up', async () => {
renderHook(() => usePendingFailures())
onSubscribed?.()
await waitFor(() => expect(getPendingFailures).toHaveBeenCalled())
table = [failure(1, 'refused')]
onTableChanged?.()
await waitFor(() => expect(shownDetails()).toEqual(['refused']))
})
it('does not show the same failure again when asked again', async () => {
table = [failure(1, 'refused')]
renderHook(() => usePendingFailures())
onSubscribed?.()
await waitFor(() => expect(shownDetails()).toEqual(['refused']))
onTableChanged?.()
focusListener?.({ payload: true })
await waitFor(() => expect(getPendingFailures).toHaveBeenCalledTimes(3))
expect(shownDetails()).toEqual(['refused'])
})
it('shows the same code again when it has failed again', async () => {
table = [failure(1, 'refused')]
renderHook(() => usePendingFailures())
onSubscribed?.()
await waitFor(() => expect(shownDetails()).toEqual(['refused']))
table = [failure(2, 'refused again')]
onTableChanged?.()
await waitFor(() => expect(shownDetails()).toEqual(['refused again']))
})
it('reads when the window takes focus', async () => {
renderHook(() => usePendingFailures())
onSubscribed?.()
await waitFor(() => expect(getPendingFailures).toHaveBeenCalled())
table = [failure(1, 'refused')]
focusListener?.({ payload: true })
await waitFor(() => expect(shownDetails()).toEqual(['refused']))
})
it('keeps a failure pending while the window is hidden', async () => {
isVisible.mockResolvedValue(false)
table = [failure(1, 'refused')]
renderHook(() => usePendingFailures())
onSubscribed?.()
await waitFor(() => expect(isVisible).toHaveBeenCalled())
expect(shownDetails()).toEqual([])
isVisible.mockResolvedValue(true)
focusListener?.({ payload: true })
await waitFor(() => expect(shownDetails()).toEqual(['refused']))
})
it('keeps a failure pending while the window is minimised', async () => {
isMinimized.mockResolvedValue(true)
table = [failure(1, 'refused')]
renderHook(() => usePendingFailures())
onSubscribed?.()
await waitFor(() => expect(isMinimized).toHaveBeenCalled())
expect(shownDetails()).toEqual([])
isMinimized.mockResolvedValue(false)
focusListener?.({ payload: true })
await waitFor(() => expect(shownDetails()).toEqual(['refused']))
})
it('keeps a failure pending when the window cannot say what it is doing', async () => {
isVisible.mockRejectedValue(new Error('no window'))
table = [failure(1, 'refused')]
renderHook(() => usePendingFailures())
onSubscribed?.()
await waitFor(() => expect(isVisible).toHaveBeenCalled())
expect(shownDetails()).toEqual([])
})
it('ignores losing focus', async () => {
renderHook(() => usePendingFailures())
onSubscribed?.()
await waitFor(() => expect(getPendingFailures).toHaveBeenCalledTimes(1))
focusListener?.({ payload: false })
expect(getPendingFailures).toHaveBeenCalledTimes(1)
})
it('leaves a failure the dialog owns out of the toasts', async () => {
table = [dialogFailure(1), failure(2, 'guard gave up')]
renderHook(() => usePendingFailures())
onSubscribed?.()
await waitFor(() => expect(shownDetails()).toEqual(['guard gave up']))
})
it('offers the dialog the failure it owns, and nothing else', async () => {
table = [failure(1, 'guard gave up'), dialogFailure(2)]
const { result } = renderHook(() => useDialogFailure())
onSubscribed?.()
await waitFor(() =>
expect(result.current.failure?.code).toBe('SYSPROXY_PRIVILEGE_REQUIRED'),
)
})
it('keeps a dismissed dialog closed while the table still holds the failure', async () => {
table = [dialogFailure(1)]
const { result } = renderHook(() => useDialogFailure())
onSubscribed?.()
await waitFor(() => expect(result.current.failure).not.toBeNull())
act(() => result.current.dismiss())
expect(result.current.failure).toBeNull()
focusListener?.({ payload: true })
await waitFor(() => expect(getPendingFailures).toHaveBeenCalledTimes(2))
expect(result.current.failure).toBeNull()
})
it('opens again when the same code fails again', async () => {
table = [dialogFailure(1)]
const { result } = renderHook(() => useDialogFailure())
onSubscribed?.()
await waitFor(() => expect(result.current.failure).not.toBeNull())
act(() => result.current.dismiss())
expect(result.current.failure).toBeNull()
table = [dialogFailure(2)]
onTableChanged?.()
await waitFor(() => expect(result.current.failure?.sequence).toBe(2))
})
@@ -0,0 +1,127 @@
import { getCurrentWindow } from '@tauri-apps/api/window'
import { useCallback, useEffect, useRef, useState } from 'react'
import { getPendingFailures, type PendingFailure } from '@/services/cmds'
import { subscribeVergeEvents } from '@/services/events'
import { showNotice } from '@/services/notice-service'
/** Failures handled by the recovery dialog instead of a toast. */
const CODES_SHOWN_AS_A_DIALOG = new Set<string>([
'SYSPROXY_PRIVILEGE_REQUIRED',
'SYSPROXY_SIDECAR_WHILE_SERVICE_READY',
])
/** Return whether a native window is visible and not minimized; fail closed. */
const windowIsWatched = async () => {
const window = getCurrentWindow()
try {
const [visible, minimized] = await Promise.all([
window.isVisible(),
window.isMinimized(),
])
return visible && !minimized
} catch (error) {
console.warn('[pending-failures] window state unavailable:', error)
return false
}
}
const usePendingFailureReader = (
onFailures: (failures: PendingFailure[]) => void,
) => {
// Avoid resubscribing when the handler changes.
const handlerRef = useRef(onFailures)
handlerRef.current = onFailures
useEffect(() => {
const read = () => {
void (async () => {
let failures: PendingFailure[]
try {
failures = await getPendingFailures()
} catch (error) {
console.warn('[pending-failures] could not be read:', error)
return
}
handlerRef.current(failures)
})()
}
const unsubscribe = subscribeVergeEvents(
{ 'verge://pending-failures-changed': read },
read,
)
const readWhenVisible = () => {
if (document.visibilityState === 'visible') read()
}
document.addEventListener('visibilitychange', readWhenVisible)
const unlistenFocus = getCurrentWindow().onFocusChanged(({ payload }) => {
if (payload) read()
})
return () => {
unsubscribe()
document.removeEventListener('visibilitychange', readWhenVisible)
void unlistenFocus.then((unlisten) => unlisten())
}
}, [])
}
/** Show each pending failure sequence once when the window can be read. */
export const usePendingFailures = () => {
const shownSequencesRef = useRef(new Map<string, number>())
const showNewFailures = useCallback(async (failures: PendingFailure[]) => {
const asToast = failures.filter(
(failure) => !CODES_SHOWN_AS_A_DIALOG.has(failure.code),
)
if (asToast.length === 0) return
if (!(await windowIsWatched())) return
for (const failure of asToast) {
const shown = shownSequencesRef.current.get(failure.code)
if (shown !== undefined && shown >= failure.sequence) continue
shownSequencesRef.current.set(failure.code, failure.sequence)
showNotice.error({ code: failure.code, detail: failure.detail })
}
}, [])
usePendingFailureReader(
useCallback(
(failures) => {
void showNewFailures(failures)
},
[showNewFailures],
),
)
}
/** Return the oldest undismissed failure owned by the dialog. */
export const useDialogFailure = () => {
const [failure, setFailure] = useState<PendingFailure | null>(null)
// Dismiss locally without retiring the backend failure.
const [dismissedSequence, setDismissedSequence] = useState<number | null>(
null,
)
usePendingFailureReader(
useCallback((failures) => {
setFailure(
failures.find((entry) => CODES_SHOWN_AS_A_DIALOG.has(entry.code)) ??
null,
)
}, []),
)
const dismiss = useCallback(() => {
setDismissedSequence(failure?.sequence ?? null)
}, [failure])
const shown =
failure && failure.sequence !== dismissedSequence ? failure : null
return { failure: shown, dismiss }
}
+6 -5
View File
@@ -61,7 +61,7 @@ import {
updateProfile,
} from '@/services/cmds'
import { subscribeVergeEvents } from '@/services/events'
import { showNotice } from '@/services/notice-service'
import { errorDetail, showNotice } from '@/services/notice-service'
import {
fetchCacheData,
revalidateQueries,
@@ -246,7 +246,7 @@ const ProfilePage = () => {
console.error('[紧急刷新] 失败:', error)
showNotice.error(
'profiles.page.feedback.notices.emergencyRefreshFailed',
{ message: String(error) },
{ message: errorDetail(error) },
4000,
)
}
@@ -297,8 +297,9 @@ const ProfilePage = () => {
} catch (initialErr) {
console.warn('[订阅导入] 首次导入失败:', initialErr)
if (String(initialErr).toLowerCase().includes('legacy tls')) {
showNotice.error(String(initialErr))
const initialDetail = errorDetail(initialErr)
if (initialDetail.toLowerCase().includes('legacy tls')) {
showNotice.error(initialErr)
return
}
@@ -316,7 +317,7 @@ const ProfilePage = () => {
// 回退导入也失败
showNotice.error(
'profiles.page.feedback.notifications.importFail',
String(retryErr),
retryErr,
)
}
} finally {
+25 -1
View File
@@ -1,6 +1,7 @@
import { invoke } from '@tauri-apps/api/core'
import dayjs from 'dayjs'
import type { CommandFailure } from '@/services/notice-service'
import { showNotice } from '@/services/notice-service'
import type { ProxyViewV1 } from '@/types/proxy-view'
import { debugLog } from '@/utils/debug'
@@ -205,7 +206,7 @@ export async function getEmbeddedServerPort() {
}
export async function changeClashCore(clashCore: string) {
return invoke<string | null>('change_clash_core', { clashCore })
return invoke<CommandFailure | null>('change_clash_core', { clashCore })
}
export async function restartCore() {
@@ -406,6 +407,29 @@ export const getRuntimeState = async () => {
return invoke<RunState>('get_runtime_state')
}
/** Operation associated with a pending failure. */
export type FailedOperation =
| 'systemProxyEnable'
| 'systemProxyDisable'
| 'systemProxyRestore'
| 'systemProxyGuard'
/** Latest unresolved failure for one stable code. */
export interface PendingFailure {
/** Stable table key. */
code: string
/** Full diagnostic chain. */
detail: string
operation: FailedOperation
/** Identity for repeated failures under the same code. */
sequence: number
}
/** Read unresolved failures without consuming them. */
export const getPendingFailures = async () => {
return invoke<PendingFailure[]>('get_pending_failures')
}
// 获取应用运行时间
export const getAppUptime = async () => {
return invoke<number>('get_app_uptime')
+2
View File
@@ -25,6 +25,8 @@ interface VergeEvents {
'verge://timer-updated': string
/** How the core is running changed; carries the whole snapshot. */
'verge://run-state-changed': RunState
/** Pending failures changed; reread the table. */
'verge://pending-failures-changed': null
/** Which profile is active changed. */
'profile-changed': string
'profile-update-started': { uid?: string }
+241
View File
@@ -0,0 +1,241 @@
import { afterEach, describe, expect, it } from 'vitest'
import {
boundNoticeText,
errorDetail,
getSnapshotNotices,
hideNotice,
showNotice,
} from '@/services/notice-service'
/** Return the last notice text that is actually rendered. */
function renderedDetail(): string | undefined {
const notices = getSnapshotNotices()
const notice = notices[notices.length - 1]
if (typeof notice?.message === 'string') return notice.message
const slot = notice?.i18n?.params?.message
return typeof slot === 'string' ? slot : undefined
}
/** Return the rendered failure notice fields. */
function renderedExplanation() {
const notices = getSnapshotNotices()
const i18n = notices[notices.length - 1]?.i18n
const readString = (value: unknown) =>
typeof value === 'string' ? value : undefined
return {
outerKey: i18n?.key,
explanationKey: readString(i18n?.params?.prefixKey),
prefix: readString(i18n?.params?.prefix),
detail: readString(i18n?.params?.message),
}
}
afterEach(() => {
getSnapshotNotices().forEach((notice) => hideNotice(notice.id))
})
describe('command failures reaching a notice', () => {
it('keeps the detail when the failure is the message', () => {
showNotice.error({
code: 'CORE_START_FAILED',
detail: 'connection refused',
})
expect(renderedDetail()).toContain('connection refused')
})
it('keeps the detail when a translation key comes first', () => {
showNotice.error('settings.feedback.errors.clash.startFailed', {
code: 'CORE_START_FAILED',
detail: 'connection refused',
})
expect(renderedDetail()).toContain('connection refused')
})
it('keeps the detail when real translation params come first', () => {
showNotice.error(
'settings.feedback.errors.clash.startFailed',
{ name: 'mihomo' },
{ code: 'CORE_START_FAILED', detail: 'connection refused' },
)
expect(renderedDetail()).toContain('connection refused')
})
it('keeps the detail for a failure that carries no code', () => {
showNotice.error('settings.feedback.errors.clash.startFailed', {
detail: 'disk full',
})
expect(renderedDetail()).toContain('disk full')
})
})
describe('system proxy failures the user can be told about', () => {
it('explains a fallback to a direct connection', () => {
showNotice.error({
code: 'SYSPROXY_DIRECT_FALLBACK',
detail: 'service could not set the proxy',
})
expect(renderedExplanation()).toEqual({
outerKey: 'shared.feedback.notices.prefixedRaw',
explanationKey: 'settings.feedback.errors.sysproxy.directFallback',
prefix: undefined,
detail: 'service could not set the proxy',
})
})
it('explains a guard that gave up', () => {
showNotice.error({
code: 'SYSPROXY_GUARD_STOPPED',
detail: 'the proxy could not be reasserted',
})
expect(renderedExplanation()).toEqual({
outerKey: 'shared.feedback.notices.prefixedRaw',
explanationKey: 'settings.feedback.errors.sysproxy.guardStopped',
prefix: undefined,
detail: 'the proxy could not be reasserted',
})
})
it('says nothing at all about a failure a dialog is already reporting', () => {
showNotice.error({
code: 'SYSPROXY_PRIVILEGE_REQUIRED',
detail: 'admin privileges required to modify system proxy',
})
showNotice.error({
code: 'SYSPROXY_SIDECAR_WHILE_SERVICE_READY',
detail: 'the core is still a sidecar',
})
expect(getSnapshotNotices()).toEqual([])
})
it('explains the cause even when the caller names the operation', () => {
showNotice.error(
'layout.components.serviceMigration.errors.restartFailed',
{
code: 'SYSPROXY_GUARD_STOPPED',
detail: 'the proxy could not be reasserted',
},
)
expect(renderedExplanation()).toEqual({
outerKey: 'shared.feedback.notices.prefixedRaw',
explanationKey: 'settings.feedback.errors.sysproxy.guardStopped',
prefix: undefined,
detail: 'the proxy could not be reasserted',
})
})
it('leaves the caller key in place for a code nothing explains', () => {
showNotice.error(
'layout.components.serviceMigration.errors.restartFailed',
{
code: 'SOME_UNMAPPED_CODE',
detail: 'connection refused',
},
)
expect(renderedExplanation()).toEqual({
outerKey: 'shared.feedback.notices.prefixedRaw',
explanationKey: 'layout.components.serviceMigration.errors.restartFailed',
prefix: undefined,
detail: 'connection refused',
})
})
it('leaves literal caller text in place, mapped code or not', () => {
showNotice.error('Could not reconnect the profile', {
code: 'SYSPROXY_GUARD_STOPPED',
detail: 'the proxy could not be reasserted',
})
expect(renderedExplanation()).toEqual({
outerKey: 'shared.feedback.notices.prefixedRaw',
explanationKey: undefined,
prefix: 'Could not reconnect the profile',
detail: 'the proxy could not be reasserted',
})
})
it('explains a guard that gave up', () => {
showNotice.error({
code: 'SYSPROXY_GUARD_STOPPED',
detail: 'service refused three times running',
})
expect(renderedExplanation()).toEqual({
outerKey: 'shared.feedback.notices.prefixedRaw',
explanationKey: 'settings.feedback.errors.sysproxy.guardStopped',
prefix: undefined,
detail: 'service refused three times running',
})
})
it('falls back to the generic message for a code nothing maps', () => {
showNotice.error({ code: 'SYSPROXY_NOT_A_REAL_CODE', detail: 'boom' })
expect(renderedExplanation()).toEqual({
outerKey: 'shared.feedback.notices.prefixedRaw',
explanationKey: 'shared.feedback.errors.operationFailed',
prefix: undefined,
detail: 'boom',
})
})
})
describe('boundNoticeText', () => {
it('leaves text that fits exactly at the limit alone', () => {
const exact = 'x'.repeat(500)
expect(boundNoticeText(exact)).toBe(exact)
})
it('marks text it had to shorten', () => {
expect(boundNoticeText('x'.repeat(501))).toBe(`${'x'.repeat(500)}…`)
})
it('does not cut a surrogate pair in half', () => {
expect(boundNoticeText('🙂'.repeat(600))).toBe(`${'🙂'.repeat(500)}…`)
})
it('does not mistake a long message for a translation key', () => {
const message = `a.${'b'.repeat(400)}`
showNotice.error(message)
expect(renderedExplanation()).toEqual({
outerKey: 'shared.feedback.notices.raw',
explanationKey: undefined,
prefix: undefined,
detail: message,
})
})
it('does not leave a space before the ellipsis', () => {
expect(boundNoticeText(`${'x'.repeat(498)} yyy`)).toBe(
`${'x'.repeat(498)}…`,
)
})
})
describe('errorDetail', () => {
it('reads the detail out of a command failure', () => {
expect(errorDetail({ code: 'X', detail: 'legacy TLS not supported' })).toBe(
'legacy TLS not supported',
)
})
it('passes plain strings through untouched', () => {
expect(errorDetail('something broke')).toBe('something broke')
})
it('still reads an Error, which not every failure path replaces', () => {
expect(errorDetail(new Error('boom'))).toBe('boom')
})
})
+159 -19
View File
@@ -1,6 +1,9 @@
import i18n from 'i18next'
import { ReactNode, isValidElement } from 'react'
import type { FailedOperation } from '@/services/cmds'
import type { TranslationKey } from '@/types/generated/i18n-keys'
type NoticeType = 'success' | 'error' | 'info'
interface NoticeTranslationDescriptor {
@@ -14,9 +17,22 @@ interface NoticeItem {
readonly duration: number
readonly message?: ReactNode
readonly i18n?: NoticeTranslationDescriptor
/** Stable classified failure code. */
readonly code?: string
/** Requested operation when known. */
readonly operation?: FailedOperation
timerId?: ReturnType<typeof setTimeout>
}
/** Failures owned by the recovery dialog. */
const CODES_A_DIALOG_REPORTS = new Set<string>([
'SYSPROXY_PRIVILEGE_REQUIRED',
'SYSPROXY_SIDECAR_WHILE_SERVICE_READY',
])
export const isReportedByDialog = (code: string | undefined): boolean =>
code !== undefined && CODES_A_DIALOG_REPORTS.has(code)
type NoticeContent = unknown
type NoticeExtra = unknown
@@ -45,8 +61,8 @@ const DEFAULT_DURATIONS: Readonly<Record<NoticeType, number>> = {
}
const TRANSLATION_KEY_PATTERN = /^[A-Za-z0-9_-]+(?:\.[A-Za-z0-9_-]+)+$/
const CODED_ERROR_PATTERN = /^CVR_ERROR:([A-Z0-9_]+)(?:\n([\s\S]*))?$/
const CODED_ERROR_TRANSLATION_KEYS: Readonly<Record<string, string>> = {
/** Localized explanation for each stable failure code. */
const CODED_ERROR_TRANSLATION_KEYS: Readonly<Record<string, TranslationKey>> = {
CLASH_CONFIG_UPDATE_FAILED:
'settings.feedback.errors.clash.configUpdateFailed',
CLASH_MODE_UPDATE_FAILED: 'settings.feedback.errors.clash.modeUpdateFailed',
@@ -70,6 +86,12 @@ const CODED_ERROR_TRANSLATION_KEYS: Readonly<Record<string, string>> = {
SERVICE_SIDECAR_FAILED: 'settings.feedback.errors.clashService.sidecarFailed',
SERVICE_UNINSTALL_FAILED:
'settings.feedback.errors.clashService.uninstallFailed',
SYSPROXY_DIRECT_FALLBACK: 'settings.feedback.errors.sysproxy.directFallback',
SYSPROXY_GUARD_STOPPED: 'settings.feedback.errors.sysproxy.guardStopped',
SYSPROXY_SIDECAR_WHILE_SERVICE_READY:
'settings.feedback.errors.sysproxy.sidecarWhileServiceReady',
SYSPROXY_PRIVILEGE_REQUIRED:
'settings.feedback.errors.sysproxy.privilegeRequired',
}
let nextId = 0
@@ -84,6 +106,8 @@ interface ParsedNoticeExtras {
params?: Record<string, unknown>
raw?: unknown
duration?: number
/** Code extracted before translation parameters are flattened. */
nestedCode?: string
}
function parseNoticeExtras(extras: NoticeExtra[]): ParsedNoticeExtras {
@@ -100,6 +124,14 @@ function parseNoticeExtras(extras: NoticeExtra[]): ParsedNoticeExtras {
continue
}
// Parse command failures before generic translation params.
if (isCommandFailure(extra)) {
if (!raw) {
raw = extra
continue
}
}
if (isPlainRecord(extra)) {
if (!params) {
params = extra
@@ -126,7 +158,35 @@ function parseNoticeExtras(extras: NoticeExtra[]): ParsedNoticeExtras {
}
}
return { params, raw, duration }
return {
params: params && readableParams(params),
raw,
duration,
nestedCode: nestedFailureCode(params),
}
}
/** Replace structured failures in translation params with readable detail. */
function readableParams(
source: Record<string, unknown>,
): Record<string, unknown> {
return Object.fromEntries(
Object.entries(source).map(([key, value]) => [
key,
isCommandFailure(value) ? value.detail : value,
]),
)
}
/** Find a classified failure nested in translation parameters. */
function nestedFailureCode(
source?: Record<string, unknown>,
): string | undefined {
if (!source) return undefined
for (const value of Object.values(source)) {
if (isCommandFailure(value) && value.code) return value.code
}
return undefined
}
function resolveDuration(type: NoticeType, override?: number) {
@@ -137,7 +197,12 @@ function buildNotice(
id: number,
type: NoticeType,
duration: number,
payload: { message?: ReactNode; i18n?: NoticeTranslationDescriptor },
payload: {
message?: ReactNode
i18n?: NoticeTranslationDescriptor
code?: string
operation?: FailedOperation
},
timerId?: ReturnType<typeof setTimeout>,
): NoticeItem {
return {
@@ -178,6 +243,23 @@ function isPlainRecord(value: unknown): value is Record<string, unknown> {
return proto === Object.prototype || proto === null
}
/** Maximum code points rendered in a notice. */
const MAX_RENDERED_TEXT_CHARS = 500
/** Bound resolved display text by code point and append an ellipsis when truncated. */
export function boundNoticeText(text: string): string {
let end = 0
let counted = 0
for (const codePoint of text) {
if (counted === MAX_RENDERED_TEXT_CHARS) {
return `${text.slice(0, end).trimEnd()}…`
}
end += codePoint.length
counted += 1
}
return text
}
function createRawDescriptor(message: string): NoticeTranslationDescriptor {
return {
key: 'shared.feedback.notices.raw',
@@ -185,8 +267,13 @@ function createRawDescriptor(message: string): NoticeTranslationDescriptor {
}
}
/** Messages longer than any real translation key are treated as raw text. */
const MAX_TRANSLATION_KEY_CHARS = 200
function isLikelyTranslationKey(key: string) {
return TRANSLATION_KEY_PATTERN.test(key)
return (
key.length <= MAX_TRANSLATION_KEY_CHARS && TRANSLATION_KEY_PATTERN.test(key)
)
}
function shouldUseTranslationKey(
@@ -210,6 +297,7 @@ function extractDisplayText(input: unknown): string | undefined {
if (input instanceof Error) {
return input.message || input.name
}
if (isCommandFailure(input)) return input.detail
if (typeof input === 'object' && input !== null) {
const maybeMessage = (input as { message?: unknown }).message
if (typeof maybeMessage === 'string') return maybeMessage
@@ -221,16 +309,40 @@ function extractDisplayText(input: unknown): string | undefined {
}
}
function parseCodedError(input?: string) {
if (!input) return undefined
const match = input.match(CODED_ERROR_PATTERN)
if (!match) return undefined
/** What a failed Tauri command reports. */
export interface CommandFailure {
/** Stable identifier for the kind of failure, when the backend could classify it. */
code?: string
/** Requested operation when known by the command. */
operation?: FailedOperation
/** Human-readable diagnostic detail. */
detail: string
}
function isCommandFailure(input: unknown): input is CommandFailure {
if (typeof input !== 'object' || input === null) return false
const candidate = input as Partial<CommandFailure>
return (
typeof candidate.detail === 'string' &&
(candidate.code === undefined || typeof candidate.code === 'string')
)
}
/** Extract display text from a structured or legacy failure. */
export function errorDetail(input: unknown): string {
return extractDisplayText(input) ?? ''
}
/** Parse a classified command failure for notice rendering. */
function parseCommandFailure(input: unknown) {
if (!isCommandFailure(input) || !input.code) return undefined
const explanation = CODED_ERROR_TRANSLATION_KEYS[input.code]
return {
translationKey:
CODED_ERROR_TRANSLATION_KEYS[match[1]] ??
'shared.feedback.errors.operationFailed',
detail: match[2]?.trim(),
translationKey: explanation ?? 'shared.feedback.errors.operationFailed',
/** Whether this code has a specific explanation. */
explained: explanation !== undefined,
detail: input.detail.trim() || undefined,
}
}
@@ -240,7 +352,7 @@ function normalizeNoticeMessage(
raw?: unknown,
): { message?: ReactNode; i18n?: NoticeTranslationDescriptor } {
const rawText = raw !== undefined ? extractDisplayText(raw) : undefined
const parsedRawError = parseCodedError(rawText)
const parsedRawError = parseCommandFailure(raw)
const rawDetail = parsedRawError?.detail ?? rawText
if (isValidElement(message)) {
@@ -248,7 +360,7 @@ function normalizeNoticeMessage(
}
if (isMaybeTranslationDescriptor(message)) {
const originalParams = message.params ?? {}
const originalParams = readableParams(message.params ?? {})
const mergedParams = Object.keys(params ?? {}).length
? { ...originalParams, ...params }
: { ...originalParams }
@@ -275,7 +387,7 @@ function normalizeNoticeMessage(
}
}
const parsedMessageError = parseCodedError(extractDisplayText(message))
const parsedMessageError = parseCommandFailure(message)
if (parsedMessageError) {
if (!parsedMessageError.detail) {
return {
@@ -298,12 +410,17 @@ function normalizeNoticeMessage(
if (typeof message === 'string') {
if (rawDetail !== undefined) {
if (shouldUseTranslationKey(message, params)) {
// A mapped cause outranks a translation key that only names the operation.
const prefixKey = parsedRawError?.explained
? parsedRawError.translationKey
: message
return {
i18n: {
key: 'shared.feedback.notices.prefixedRaw',
params: {
...(params ?? {}),
prefixKey: message,
prefixKey,
message: rawDetail,
},
},
@@ -351,7 +468,12 @@ const baseShowNotice = (
...extras: NoticeExtra[]
): number => {
const id = nextId++
const { params, raw, duration } = parseNoticeExtras(extras)
const { params, raw, duration, nestedCode } = parseNoticeExtras(extras)
// Accept codes from raw, direct, or interpolated failures.
const code = failureCode(raw) ?? failureCode(message) ?? nestedCode
const operation = failureOperation(raw) ?? failureOperation(message)
// Suppress duplicate toasts while preserving the caller's id contract.
if (isReportedByDialog(code)) return id
const effectiveDuration = resolveDuration(type, duration)
const timerId =
effectiveDuration > 0
@@ -363,15 +485,33 @@ const baseShowNotice = (
id,
type,
effectiveDuration,
normalizedMessage,
{ ...normalizedMessage, code, operation },
timerId,
)
// Replace older notices for the same failure code.
if (code) {
notices
.filter((existing) => existing.code === code)
.forEach((existing) => {
if (existing.timerId) clearTimeout(existing.timerId)
})
notices = notices.filter((existing) => existing.code !== code)
}
notices = [...notices, notice]
notifySubscribers()
return id
}
function failureCode(input: unknown): string | undefined {
return isCommandFailure(input) ? input.code : undefined
}
function failureOperation(input: unknown): FailedOperation | undefined {
return isCommandFailure(input) ? input.operation : undefined
}
/**
* Shows a global notice; `showNotice.success / error / info` are the usual entry points.
*
+40
View File
@@ -0,0 +1,40 @@
/** Why a privileged service is needed. */
export type ServiceRequestReason =
| 'sysproxyRefused'
| 'sysproxySidecarReady'
| 'tunNeedsService'
export interface ServiceRequest {
readonly reason: ServiceRequestReason
/** Settings to apply after the core enters service mode. */
readonly restore?: Partial<IVergeConfig>
}
type Subscriber = () => void
let request: ServiceRequest | null = null
const subscribers = new Set<Subscriber>()
const notify = () => {
subscribers.forEach((subscriber) => subscriber())
}
export const requestService = (next: ServiceRequest) => {
request = next
notify()
}
export const clearServiceRequest = () => {
if (request === null) return
request = null
notify()
}
export const subscribeServiceRequest = (subscriber: Subscriber) => {
subscribers.add(subscriber)
return () => {
subscribers.delete(subscriber)
}
}
export const getServiceRequest = () => request
+18
View File
@@ -138,6 +138,16 @@ export const translationKeys = [
'layout.components.serviceMigration.errors.restartFailed',
'layout.components.serviceMigration.errors.revalidationFailed',
'layout.components.serviceMigration.errors.sidecarFailed',
'layout.components.sysproxyPrivilege.title',
'layout.components.sysproxyPrivilege.message',
'layout.components.sysproxyPrivilege.serviceReadyMessage',
'layout.components.sysproxyPrivilege.alternative',
'layout.components.sysproxyPrivilege.later',
'layout.components.sysproxyPrivilege.installing',
'layout.components.sysproxyPrivilege.restarting',
'layout.components.sysproxyPrivilege.applying',
'layout.components.sysproxyPrivilege.tunTitle',
'layout.components.sysproxyPrivilege.tunMessage',
'layout.feedback.errors.restartCoreStopFailed',
'layout.feedback.errors.quitCoreStopFailed',
'logs.page.title',
@@ -397,8 +407,12 @@ export const translationKeys = [
'settings.sections.proxyControl.tooltips.tunUnavailable',
'settings.sections.proxyControl.actions.installService',
'settings.sections.proxyControl.actions.uninstallService',
'settings.sections.proxyControl.actions.switchToServiceMode',
'settings.sections.proxyControl.fields.systemProxy',
'settings.sections.proxyControl.fields.tunMode',
'settings.sections.proxyControl.messages.installedCheckProxy',
'settings.sections.proxyControl.messages.installedCoreNotOnService',
'settings.sections.proxyControl.messages.installedProxyRestored',
'settings.sections.externalController.title',
'settings.sections.externalController.fields.enable',
'settings.sections.externalController.fields.address',
@@ -760,6 +774,10 @@ export const translationKeys = [
'settings.feedback.errors.clashService.reinstallFailed',
'settings.feedback.errors.clashService.repairFailed',
'settings.feedback.errors.clashService.sidecarFailed',
'settings.feedback.errors.sysproxy.privilegeRequired',
'settings.feedback.errors.sysproxy.directFallback',
'settings.feedback.errors.sysproxy.guardStopped',
'settings.feedback.errors.sysproxy.sidecarWhileServiceReady',
'settings.feedback.notifications.clash.restartSuccess',
'settings.feedback.notifications.clash.versionUpdated',
'settings.feedback.notifications.clash.alreadyLatestVersion',
+24
View File
@@ -231,6 +231,18 @@ export interface TranslationResources {
title: string
unavailableMessage: string
}
sysproxyPrivilege: {
alternative: string
applying: string
installing: string
later: string
message: string
restarting: string
serviceReadyMessage: string
title: string
tunMessage: string
tunTitle: string
}
}
feedback: {
errors: {
@@ -796,6 +808,12 @@ export interface TranslationResources {
sidecarFailed: string
uninstallFailed: string
}
sysproxy: {
directFallback: string
guardStopped: string
privilegeRequired: string
sidecarWhileServiceReady: string
}
}
notifications: {
clash: {
@@ -1297,12 +1315,18 @@ export interface TranslationResources {
proxyControl: {
actions: {
installService: string
switchToServiceMode: string
uninstallService: string
}
fields: {
systemProxy: string
tunMode: string
}
messages: {
installedCheckProxy: string
installedCoreNotOnService: string
installedProxyRestored: string
}
tooltips: {
systemProxy: string
tunMode: string