mirror of
https://github.com/clash-verge-rev/clash-verge-rev.git
synced 2026-11-19 02:12:10 +08:00
refactor: Rewrite and improve sysproxy logic (#7744)
* fix(cmd): preserve anyhow context in coded errors Use alternate error formatting so coded failures retain the full anyhow context chain without changing their wire format. * fix(macos): skip redundant proxy disable writes When both proxy modes are off, read macOS state first and skip networksetup if the OS is already clean. Update the guard target only after a successful write. * feat(proxy): classify system proxy failures Attach stable, actionable proxy failure codes to anyhow chains while preserving the original diagnostic causes. * feat(cmd): return structured command failures Replace encoded error strings with serializable code and detail fields, and update frontend notice consumers to handle the structured shape. * fix(scripts): use the js-yaml namespace import Import js-yaml through its ESM namespace so the i18n cleanup script can access load and dump. * feat(proxy): localize classified proxy failures Map privilege and direct-fallback codes to localized explanations, and let mapped causes outrank generic operation keys in notices. * fix(ui): bound notice text and render failure details Limit resolved notice text without truncating clipboard content, and normalize structured failures embedded in translation parameters. * feat(proxy): persist unseen proxy failures Store unresolved classified failures by code, notify the frontend when the table changes, and show each failure sequence once when a visible window can receive it. * feat(proxy): report tray and hotkey toggle failures Record classified failures from tray and hotkey proxy toggles so they appear when a visible window is available. * fix(ui): restore the proxy switch after failed toggles Refresh frontend proxy state after a failed toggle so the switch reflects the rolled-back configuration. * feat(proxy): stop the guard after repeated failures Report guard outcomes, stop after the failure threshold, and persist the classified failure for the frontend. * fix(macos): preserve proxy during service handoff Stop a sidecar being handed to the service without clearing proxy state that the new owner must inherit. * feat(macos): classify misplaced sidecar state Distinguish a refused sidecar proxy write from a machine that still needs the privileged service installed. * feat(ui): recover misplaced sidecar notices Offer a restart action for macOS proxy failures caused by a ready service while the core still runs as a sidecar. * feat(ui): install the service from proxy notices Let privilege notices install the macOS service, restart the core, and report the runtime mode that was actually reached. * feat(cmd): attach requested proxy operations Carry the requested proxy direction with structured command failures when the originating command knows it. * feat(sysproxy): drain guards before OS access Wait for the local proxy guard to stop before OS reads, service handoff, or final writes, and refuse transitions when it does not drain. * feat(sysproxy): recover partial proxy writes Use write progress to choose whether to restore the old guard or compensate with a disabled proxy state, while preserving actionable errors. * feat(sysproxy): skip already-applied proxy writes Compare macOS proxy snapshots with global, PAC, and disabled targets so matching state avoids redundant privileged writes. * feat(proxy): report background proxy failures Persist and surface classified proxy failures from lifecycle paths that have no direct caller awaiting the result. * feat(ui): move proxy recovery into a dialog Guide users through installing or switching to the service after a refused proxy write, and suppress duplicate toast reports. * fix(ui): close proxy dialog after service recovery Dismiss the recovery dialog once the core reaches service mode, even when the original proxy request remains pending. * feat(ui): retry proxy request after service recovery Replay the requested proxy direction after the core reaches service mode, while leaving incidental restores unchanged. * fix(proxy): refresh state after successful apply Publish the proxy refresh from the shared apply path after releasing the lifecycle lock, and remove the tray-specific duplicate. * feat(ui): show proxy recovery progress Display installation, restart, and proxy-apply stages while keeping the primary action spinner visible during recovery. * feat(ui): route unavailable TUN through service recovery Let the TUN switch request service recovery and restore its requested state after the core restarts in service mode. * fix(ui): avoid duplicate TUN recovery errors Roll back deferred TUN toggles without reporting an error, and publish configuration refreshes from the transaction commit path. * chore: update changelog & pinlock * fix(core): resolve platform-specific clippy warnings * fix(core): detect Windows wildcard TCP conflicts Windows permits a specific exclusive bind beside an existing non-exclusive wildcard listener. Consult the system TCP listener table so the probe reports that overlap as a conflict.
This commit is contained in:
+25
-1
@@ -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')
|
||||
|
||||
@@ -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 }
|
||||
|
||||
@@ -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
@@ -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.
|
||||
*
|
||||
|
||||
@@ -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
|
||||
Reference in New Issue
Block a user