mirror of
https://github.com/clash-verge-rev/clash-verge-rev.git
synced 2026-11-21 11:42:09 +08:00
refactor(frontend): contract flow (#8131)
* feat(contract): export wire contract from backend and generate frontend types Adds a zero-dependency `frontend-contract` bin that serializes the real NoticeStatus variants and FrontendEvent payloads, scripts/gen-contract.mjs which emits the committed src/services/contract.ts, and a CI job that regenerates it and fails on a non-empty diff. events.ts now derives its event map from the generated contract instead of hand-typed shapes. * feat(events): route all backend events through a single event bus and store Adds src/services/bus (the only listen/emit site: one handler per contract event plus the frontend-internal test-all event) and the React context/reducer app store. Migrates the five scattered subscriptions (layout events, pending failures, proxy refresh, profile update/timer, test-all), deletes the old glue (events.ts, use-listen, use-layout-events, LoadingCacheProvider), moves run state into the store, and adds an architecture gate script wired into CI. Behavior is unchanged; the run-state query's poll/focus safety net is preserved by the store provider. * refactor(notice): make the notice table exhaustive and drop dead wire entries D5 cleanup, frontend and backend in one commit: removes the six config_validate::* statuses that never receive a backend send and the set_config::ok send (enum variants, golden list 41→34, send point in restart_clash_core), their frontend handlers, and the five i18n keys only those handlers used. The notice table is now typed as a Record over the generated NoticeStatus union, so a status without a frontend entry fails to compile. The info status (sent by the silent updater for breaking change notices, previously dropped with a console warning) now shows an info toast — the one deliberate behavior delta. * feat(mutate): single funnel for user-intent commands and invoke gate Adds src/services/mutate.ts: one path for optimistic apply, services-layer invoke, Busy handling, failure rollback, and the error toast, with busy bookkeeping mirrored into the app store. The patch hooks (verge, clash, profiles) now route through it. Moves the remaining direct invokes (unlock ×3, DNS ×4) into cmds.ts and turns on the invoke-only-in-services architecture gate in CI. * refactor(settings): route settings-domain commands through the mutate funnel Ports port saving, webdav/local backup operations, core change/restart/ upgrade, service install/uninstall/repair flows, the system-proxy toggle queue, the DNS override toggle, and app lifecycle commands onto the single funnel. Bespoke flows keep their own error handling via errorNotice:false; simple flows gain the funnel's default error toast and revalidation. * refactor(profiles): route profile operations through the mutate funnel Ports profile create/import/reorder/delete/update/patch/save-file and enhance calls onto the funnel; retry and editor flows keep their own error handling with errorNotice:false. Per-uid ids keep the update worker pool concurrent under the funnel's in-flight dedupe. * refactor(proxies): route proxy/home/misc commands through the mutate funnel Ports mode switching (page and home card), chain runtime updates, node selection with tray sync, selection recording, provider updates and syncs, and lightweight-mode entry onto the funnel; every site keeps its existing optimistic/revert and error-handling behavior. * docs: add frontend architecture guardrails for src Layering rules for the contract flow: generated contract as the only wire-typing source, event bus as the only listen/emit site, pure-reducer store for event-derived state, the mutate funnel for user intent, and invoke only in the services layer — each backed by the CI gates. * fix(events): close run-state race and restore single error toasts Self-review findings: the bus now re-reads the run-state snapshot in onSubscribed so an event racing the store's initial read cannot leave a stale snapshot (the ordering the old layout listener guaranteed), and the patch hooks pass errorNotice:false so GuardState/page handlers remain the only error toast, matching the pre-migration behavior. * fix(frontend): preserve queued intents and fresh runtime snapshots * refactor(frontend): trim unused mutation and busy state APIs * docs(frontend): focus guardrails on architecture ownership
This commit is contained in:
@@ -0,0 +1,200 @@
|
||||
import { beforeEach, expect, it, vi } from 'vitest'
|
||||
|
||||
import {
|
||||
type RunState,
|
||||
getCoreStartupError,
|
||||
takeDnsOverrideNotice,
|
||||
takeServiceFallbackNotice,
|
||||
takeServiceRepairNotice,
|
||||
} from '@/services/cmds'
|
||||
import { showNotice } from '@/services/notice-service'
|
||||
import { revalidateQueries } from '@/services/query-client'
|
||||
import { requestService } from '@/services/service-request'
|
||||
import type { AppStoreAction } from '@/store/app-state'
|
||||
|
||||
const nativeWindow = vi.hoisted(() => ({
|
||||
isVisible: vi.fn().mockResolvedValue(true),
|
||||
isMinimized: vi.fn().mockResolvedValue(false),
|
||||
}))
|
||||
vi.mock('@tauri-apps/api/window', () => ({
|
||||
getCurrentWindow: () => nativeWindow,
|
||||
}))
|
||||
vi.mock('@/services/cmds', () => ({
|
||||
getCoreStartupError: vi.fn().mockResolvedValue(null),
|
||||
getPendingFailures: vi.fn().mockResolvedValue([]),
|
||||
takeDiscardedKeysNotice: vi.fn().mockResolvedValue(null),
|
||||
takeDnsOverrideNotice: vi.fn().mockResolvedValue(false),
|
||||
takeServiceFallbackNotice: vi.fn().mockResolvedValue(null),
|
||||
takeServiceRepairNotice: vi.fn().mockResolvedValue(false),
|
||||
takeServiceOwnerNotice: vi.fn().mockResolvedValue(null),
|
||||
}))
|
||||
vi.mock('@/services/service-request', () => ({ requestService: vi.fn() }))
|
||||
vi.mock('@/services/notice-service', () => ({
|
||||
showNotice: { info: vi.fn(), error: vi.fn(), warning: vi.fn() },
|
||||
}))
|
||||
vi.mock('@/services/query-client', () => ({
|
||||
revalidateQueries: vi.fn(),
|
||||
}))
|
||||
|
||||
const flush = () => new Promise((resolve) => setTimeout(resolve, 0))
|
||||
|
||||
// Everything (bus + notice handlers) comes from one fresh module registry per
|
||||
// test: startup-error dedup state is module-scoped in notice-handlers.
|
||||
const mountBus = async () => {
|
||||
vi.resetModules()
|
||||
const [{ createEventBus }, { handleNoticeMessage: notice }] =
|
||||
await Promise.all([
|
||||
import('./create-bus-handlers'),
|
||||
import('@/services/notice-handlers'),
|
||||
])
|
||||
const dispatch = vi.fn<(action: AppStoreAction) => void>()
|
||||
return createEventBus({
|
||||
dispatch,
|
||||
handleNotice: ([status, message]: [string, string]) => {
|
||||
notice(status, message, (key) => key, vi.fn())
|
||||
},
|
||||
revalidateKeys: (keys) => void revalidateQueries(keys.map((key) => [key])),
|
||||
readPendingFailures: () => {},
|
||||
readRunState: () => {},
|
||||
})
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
vi.mocked(getCoreStartupError).mockResolvedValue(null)
|
||||
nativeWindow.isVisible.mockResolvedValue(true)
|
||||
nativeWindow.isMinimized.mockResolvedValue(false)
|
||||
})
|
||||
|
||||
it('does not replay a recovered startup error after WebView recreation', async () => {
|
||||
const first = await import('@/services/notice-handlers')
|
||||
vi.mocked(getCoreStartupError).mockResolvedValue({
|
||||
kind: 'startFailed',
|
||||
detail: 'startup failed',
|
||||
})
|
||||
first.handleNoticeMessage('core_start::error', '', (key) => key, vi.fn())
|
||||
await flush()
|
||||
expect(showNotice.error).toHaveBeenCalledOnce()
|
||||
|
||||
// Mocked modules share one instance across resetModules; the notice-handlers
|
||||
// module state is what a WebView recreation actually resets.
|
||||
vi.mocked(getCoreStartupError).mockResolvedValue(null)
|
||||
vi.resetModules()
|
||||
const recreated = await import('@/services/notice-handlers')
|
||||
recreated.handleNoticeMessage('core_start::error', '', (key) => key, vi.fn())
|
||||
await flush()
|
||||
expect(showNotice.error).toHaveBeenCalledOnce()
|
||||
})
|
||||
|
||||
it.each([
|
||||
['hidden', false, false],
|
||||
['minimized', true, true],
|
||||
] as const)(
|
||||
'keeps a %s-window startup error until the window is restored',
|
||||
async (_state, visible, minimized) => {
|
||||
const detail = 'startup failed'
|
||||
nativeWindow.isVisible.mockResolvedValue(visible)
|
||||
nativeWindow.isMinimized.mockResolvedValue(minimized)
|
||||
vi.mocked(getCoreStartupError).mockResolvedValue({
|
||||
kind: 'startFailed',
|
||||
detail,
|
||||
})
|
||||
const bus = await mountBus()
|
||||
bus.onSubscribed()
|
||||
bus.handlers['verge://notice-message'](['core_start::error', ''])
|
||||
await flush()
|
||||
expect(showNotice.error).not.toHaveBeenCalled()
|
||||
nativeWindow.isVisible.mockResolvedValue(true)
|
||||
nativeWindow.isMinimized.mockResolvedValue(false)
|
||||
bus.onWindowFocus()
|
||||
await flush()
|
||||
expect(showNotice.error).toHaveBeenCalledExactlyOnceWith(
|
||||
'settings.feedback.errors.clash.startFailed',
|
||||
detail,
|
||||
)
|
||||
},
|
||||
)
|
||||
|
||||
it('delivers an early core startup failure once after listeners mount', async () => {
|
||||
const detail = 'could not open core execution mutex: access denied'
|
||||
vi.mocked(getCoreStartupError).mockResolvedValue({
|
||||
kind: 'startFailed',
|
||||
detail,
|
||||
})
|
||||
const bus = await mountBus()
|
||||
bus.onSubscribed()
|
||||
bus.handlers['verge://notice-message'](['core_start::error', ''])
|
||||
await flush()
|
||||
expect(showNotice.error).toHaveBeenCalledExactlyOnceWith(
|
||||
'settings.feedback.errors.clash.startFailed',
|
||||
detail,
|
||||
)
|
||||
})
|
||||
|
||||
it('shows the same core failure again after the core has started in between', async () => {
|
||||
const failure = { kind: 'serviceCoreStopped', detail: 'stopped' } as const
|
||||
vi.mocked(getCoreStartupError).mockResolvedValue(failure)
|
||||
const bus = await mountBus()
|
||||
bus.handlers['verge://notice-message'](['core_start::error', ''])
|
||||
await flush()
|
||||
|
||||
// The core started and stopped again before the window handled either event.
|
||||
bus.handlers['verge://run-state-changed']({ mode: 'Service' } as RunState)
|
||||
bus.handlers['verge://notice-message'](['core_start::error', ''])
|
||||
await flush()
|
||||
expect(showNotice.error).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
|
||||
it('drains a DNS notice after listeners mount without duplicating its live event', async () => {
|
||||
vi.mocked(takeDnsOverrideNotice)
|
||||
.mockResolvedValueOnce(true)
|
||||
.mockResolvedValue(false)
|
||||
|
||||
const bus = await mountBus()
|
||||
|
||||
expect(takeDnsOverrideNotice).not.toHaveBeenCalled()
|
||||
bus.onSubscribed()
|
||||
expect(takeDnsOverrideNotice).toHaveBeenCalledOnce()
|
||||
bus.handlers['verge://notice-message'](['dns_override::auto_disabled', ''])
|
||||
await flush()
|
||||
|
||||
expect(showNotice.info).toHaveBeenCalledExactlyOnceWith(
|
||||
'settings.modals.dns.protection.autoDisabled',
|
||||
)
|
||||
expect(revalidateQueries).toHaveBeenCalledWith([['getVergeConfig']])
|
||||
})
|
||||
|
||||
it('offers service reinstallation for a startup path refusal even before listeners mount', async () => {
|
||||
vi.mocked(takeServiceRepairNotice)
|
||||
.mockResolvedValueOnce(true)
|
||||
.mockResolvedValue(false)
|
||||
|
||||
const bus = await mountBus()
|
||||
|
||||
bus.onSubscribed()
|
||||
bus.handlers['verge://notice-message'](['service_core::repair_required', ''])
|
||||
await flush()
|
||||
|
||||
expect(requestService).toHaveBeenCalledExactlyOnceWith({
|
||||
reason: 'serviceLocationRefused',
|
||||
})
|
||||
})
|
||||
|
||||
it('explains a startup core rejection instead of the generic fallback notice', async () => {
|
||||
const reason =
|
||||
'approved core was rejected: core path "C:\\" has an untrusted write ACE'
|
||||
vi.mocked(takeServiceFallbackNotice)
|
||||
.mockResolvedValueOnce({ kind: 'coreRejected', reason })
|
||||
.mockResolvedValue(null)
|
||||
|
||||
const bus = await mountBus()
|
||||
bus.onSubscribed()
|
||||
bus.handlers['verge://notice-message'](['service_core::sidecar_fallback', ''])
|
||||
await flush()
|
||||
|
||||
expect(showNotice.warning).toHaveBeenCalledExactlyOnceWith(
|
||||
'settings.feedback.notifications.clashService.permissionFallback',
|
||||
{ reason },
|
||||
0,
|
||||
)
|
||||
})
|
||||
@@ -0,0 +1,120 @@
|
||||
import type { VergeEventPayloads } from '@/services/contract'
|
||||
import { forgetShownStartupError } from '@/services/notice-handlers'
|
||||
import type { AppStoreAction } from '@/store/app-state'
|
||||
|
||||
/** Frontend-internal event: home test card → test items. Not in the backend contract. */
|
||||
export const TEST_ALL_EVENT = 'verge://test-all'
|
||||
|
||||
type BusEventName = keyof VergeEventPayloads | typeof TEST_ALL_EVENT
|
||||
|
||||
type BusHandlers = {
|
||||
[Name in BusEventName]: (
|
||||
payload: Name extends keyof VergeEventPayloads
|
||||
? VergeEventPayloads[Name]
|
||||
: null,
|
||||
) => void
|
||||
}
|
||||
|
||||
export interface BusHandlerDeps {
|
||||
dispatch: (action: AppStoreAction) => void
|
||||
/** Notice-table entry point; layout owns t/navigate wiring. */
|
||||
handleNotice: (payload: [string, string]) => void
|
||||
revalidateKeys: (keys: readonly string[]) => void
|
||||
/** Re-read the backend pending-failure snapshot into the store. */
|
||||
readPendingFailures: () => void
|
||||
/** Re-read the run-state snapshot into the store. */
|
||||
readRunState: () => void
|
||||
}
|
||||
|
||||
/**
|
||||
* Pure per-event handler table for the bus. Handlers may trigger documented
|
||||
* side effects (SWR revalidation, notice toasts) but write store state only
|
||||
* through dispatched pure actions. Created exactly once per bus mount; the
|
||||
* throttles below live in the returned closure, mirroring the previous
|
||||
* scattered listeners.
|
||||
*/
|
||||
export const createEventBus = (deps: BusHandlerDeps) => {
|
||||
let lastProfileId: string | null = null
|
||||
let lastProfileChangeTime = 0
|
||||
let lastProxyRefreshTime = 0
|
||||
const refreshThrottle = 800
|
||||
|
||||
const handleProfileChanged = (newProfileId: string) => {
|
||||
const now = Date.now()
|
||||
if (
|
||||
lastProfileId === newProfileId &&
|
||||
now - lastProfileChangeTime < refreshThrottle
|
||||
) {
|
||||
return
|
||||
}
|
||||
lastProfileId = newProfileId
|
||||
lastProfileChangeTime = now
|
||||
deps.revalidateKeys(['getProfiles'])
|
||||
}
|
||||
|
||||
const handleRefreshProxyConfig = () => {
|
||||
const now = Date.now()
|
||||
if (now - lastProxyRefreshTime <= refreshThrottle) return
|
||||
lastProxyRefreshTime = now
|
||||
deps.revalidateKeys(['getProxyView'])
|
||||
}
|
||||
|
||||
const handlers: BusHandlers = {
|
||||
'verge://refresh-clash-config': () =>
|
||||
deps.revalidateKeys([
|
||||
'getProxyView',
|
||||
'getVersion',
|
||||
'getClashConfig',
|
||||
'getClashInfo',
|
||||
'getClashMode',
|
||||
'getRuntimeConfig',
|
||||
'getRules',
|
||||
'getRuleProviders',
|
||||
]),
|
||||
'verge://refresh-verge-config': () =>
|
||||
deps.revalidateKeys([
|
||||
'getVergeConfig',
|
||||
'getSystemProxy',
|
||||
'getAutotemProxy',
|
||||
]),
|
||||
'verge://refresh-profiles': () => deps.revalidateKeys(['getProfiles']),
|
||||
'verge://refresh-proxy-config': handleRefreshProxyConfig,
|
||||
'verge://notice-message': (payload) => deps.handleNotice(payload),
|
||||
'profile-changed': handleProfileChanged,
|
||||
'verge://timer-updated': (uid) =>
|
||||
deps.dispatch({ type: 'profileUpdate/timerTick', uid }),
|
||||
'profile-update-started': ({ uid }) =>
|
||||
deps.dispatch({ type: 'profileUpdate/started', uid }),
|
||||
'profile-update-completed': ({ uid }) => {
|
||||
deps.dispatch({ type: 'profileUpdate/completed', uid })
|
||||
deps.revalidateKeys(['getProfiles'])
|
||||
},
|
||||
'verge://run-state-changed': (payload) => {
|
||||
deps.dispatch({ type: 'runState/loaded', runState: payload })
|
||||
// A running core resolves every failure shown before it.
|
||||
if (payload.mode !== 'NotRunning') forgetShownStartupError()
|
||||
},
|
||||
'verge://pending-failures-changed': () => deps.readPendingFailures(),
|
||||
[TEST_ALL_EVENT]: () => deps.dispatch({ type: 'testAll/requested' }),
|
||||
}
|
||||
|
||||
const onSubscribed = () => {
|
||||
// Run state is read after subscribing so an event racing the store's
|
||||
// initial read cannot leave a stale snapshot behind.
|
||||
deps.readRunState()
|
||||
deps.revalidateKeys(['getVergeConfig'])
|
||||
deps.readPendingFailures()
|
||||
deps.handleNotice(['dns_override::auto_disabled', ''])
|
||||
deps.handleNotice(['enhance::discarded_keys', ''])
|
||||
deps.handleNotice(['service_core::sidecar_fallback', ''])
|
||||
deps.handleNotice(['service_core::repair_required', ''])
|
||||
deps.handleNotice(['service_core::app_data_not_owned', ''])
|
||||
deps.handleNotice(['core_start::error', ''])
|
||||
}
|
||||
|
||||
const onWindowFocus = () => {
|
||||
deps.handleNotice(['core_start::error', ''])
|
||||
}
|
||||
|
||||
return { handlers, onSubscribed, onWindowFocus }
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
import { emit } from '@tauri-apps/api/event'
|
||||
|
||||
import { TEST_ALL_EVENT } from './create-bus-handlers'
|
||||
|
||||
export { useEventBus } from './use-event-bus'
|
||||
|
||||
/** The only emitter of the frontend-internal test-all event. */
|
||||
export const emitTestAll = () => {
|
||||
void emit(TEST_ALL_EVENT)
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
import { beforeEach, expect, it, vi } from 'vitest'
|
||||
|
||||
import { createStoreReads } from '@/store/store-reads'
|
||||
|
||||
import { useEventBus } from './use-event-bus'
|
||||
|
||||
const listen = vi.hoisted(() =>
|
||||
vi.fn<
|
||||
(name: string, handler: (event: unknown) => void) => Promise<() => void>
|
||||
>(() => Promise.resolve(() => {})),
|
||||
)
|
||||
const handleNotice = vi.hoisted(() => vi.fn())
|
||||
const dispatch = vi.hoisted(() => vi.fn())
|
||||
|
||||
vi.mock('@tauri-apps/api/event', () => ({ listen }))
|
||||
vi.mock('@tauri-apps/api/window', () => ({
|
||||
getCurrentWindow: () => ({
|
||||
onFocusChanged: vi.fn(() => Promise.resolve(() => {})),
|
||||
}),
|
||||
}))
|
||||
vi.mock('react', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('react')>()
|
||||
return {
|
||||
...actual,
|
||||
useEffect: (effect: () => void | (() => void)) => effect(),
|
||||
}
|
||||
})
|
||||
vi.mock('@/store/app-store-context', () => ({
|
||||
useAppDispatch: () => dispatch,
|
||||
useAppReads: () => createStoreReads(dispatch),
|
||||
}))
|
||||
vi.mock('@/services/cmds', () => ({
|
||||
getPendingFailures: vi.fn().mockResolvedValue([]),
|
||||
getSidecarFailure: vi.fn().mockResolvedValue({ revision: 0, detail: null }),
|
||||
getRuntimeState: vi.fn().mockResolvedValue({ mode: 'NotRunning' }),
|
||||
}))
|
||||
vi.mock('@/services/query-client', () => ({ revalidateQueries: vi.fn() }))
|
||||
|
||||
const flush = () => new Promise((resolve) => setTimeout(resolve, 0))
|
||||
|
||||
beforeEach(() => {
|
||||
listen.mockClear()
|
||||
handleNotice.mockClear()
|
||||
dispatch.mockClear()
|
||||
listen.mockImplementation(() => Promise.resolve(() => {}))
|
||||
})
|
||||
|
||||
it('drains event-only state only after every listener is registered', async () => {
|
||||
const registrations: Array<() => void> = []
|
||||
listen.mockImplementation(
|
||||
() =>
|
||||
new Promise((resolve) => {
|
||||
registrations.push(() => resolve(() => {}))
|
||||
}),
|
||||
)
|
||||
|
||||
useEventBus(handleNotice)
|
||||
await flush()
|
||||
expect(handleNotice).not.toHaveBeenCalled()
|
||||
|
||||
for (const resolve of registrations.slice(0, -1)) resolve()
|
||||
await flush()
|
||||
expect(handleNotice).not.toHaveBeenCalled()
|
||||
|
||||
registrations.at(-1)?.()
|
||||
await flush()
|
||||
expect(handleNotice).toHaveBeenCalled()
|
||||
expect(dispatch).toHaveBeenCalledWith({
|
||||
type: 'pendingFailures/loaded',
|
||||
failures: [],
|
||||
})
|
||||
expect(dispatch).toHaveBeenCalledWith({
|
||||
type: 'sidecarFailure/loaded',
|
||||
snapshot: { revision: 0, detail: null },
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,70 @@
|
||||
import { listen, type UnlistenFn } from '@tauri-apps/api/event'
|
||||
import { getCurrentWindow } from '@tauri-apps/api/window'
|
||||
import { useEffect } from 'react'
|
||||
|
||||
import { revalidateQueries } from '@/services/query-client'
|
||||
import { useAppDispatch, useAppReads } from '@/store/app-store-context'
|
||||
|
||||
import { createEventBus } from './create-bus-handlers'
|
||||
|
||||
/**
|
||||
* Mounts the event bus exactly once (layout root): one `listen` per contract
|
||||
* event plus the frontend-internal test-all event. Replaces every scattered
|
||||
* subscription; teardown disposes late-resolving registrations.
|
||||
*/
|
||||
export const useEventBus = (
|
||||
handleNotice: (payload: [string, string]) => void,
|
||||
) => {
|
||||
const dispatch = useAppDispatch()
|
||||
const reads = useAppReads()
|
||||
|
||||
useEffect(() => {
|
||||
const revalidateKeys = (keys: readonly string[]) => {
|
||||
void revalidateQueries(keys.map((key) => [key]))
|
||||
}
|
||||
const { readPendingFailures } = reads
|
||||
const readRunState = () => {
|
||||
void reads.readRunState().catch(() => {})
|
||||
}
|
||||
|
||||
const bus = createEventBus({
|
||||
dispatch,
|
||||
handleNotice,
|
||||
revalidateKeys,
|
||||
readPendingFailures,
|
||||
readRunState,
|
||||
})
|
||||
|
||||
let disposed = false
|
||||
const unlisteners: UnlistenFn[] = []
|
||||
const registrations = (
|
||||
Object.keys(bus.handlers) as Array<keyof typeof bus.handlers>
|
||||
).map((name) =>
|
||||
listen(name, ({ payload }) => {
|
||||
;(bus.handlers[name] as (payload: unknown) => void)(payload)
|
||||
}).then((unlisten) => {
|
||||
if (disposed) {
|
||||
unlisten()
|
||||
return
|
||||
}
|
||||
unlisteners.push(unlisten)
|
||||
}),
|
||||
)
|
||||
|
||||
// Re-read event-only state after subscribing to close the initial race window.
|
||||
void Promise.all(registrations).then(() => {
|
||||
if (disposed) return
|
||||
bus.onSubscribed()
|
||||
})
|
||||
|
||||
const unlistenFocus = getCurrentWindow().onFocusChanged(({ payload }) => {
|
||||
if (payload) bus.onWindowFocus()
|
||||
})
|
||||
|
||||
return () => {
|
||||
disposed = true
|
||||
for (const unlisten of unlisteners.splice(0)) unlisten()
|
||||
void unlistenFocus.then((unlisten) => unlisten())
|
||||
}
|
||||
}, [dispatch, handleNotice, reads])
|
||||
}
|
||||
@@ -183,6 +183,22 @@ export async function setDnsOverride(
|
||||
>('set_dns_override', { profileUid, enabled, confirmation })
|
||||
}
|
||||
|
||||
export async function getDnsConfigContent() {
|
||||
return invoke<string | null>('get_dns_config_content')
|
||||
}
|
||||
|
||||
export async function saveDnsConfig(dnsConfig: Record<string, unknown>) {
|
||||
return invoke<void>('save_dns_config', { dnsConfig })
|
||||
}
|
||||
|
||||
export async function validateDnsConfig() {
|
||||
return invoke<ValidationOutcome>('validate_dns_config')
|
||||
}
|
||||
|
||||
export async function applyDnsConfig(apply: boolean) {
|
||||
return invoke<void>('apply_dns_config', { apply })
|
||||
}
|
||||
|
||||
export async function takeDnsOverrideNotice() {
|
||||
return invoke<boolean>('take_dns_override_notice')
|
||||
}
|
||||
@@ -568,3 +584,22 @@ export const probeListener = async (request: ListenerProbe) => {
|
||||
export const saveProxyPorts = async (settings: ProxyPortSettings) => {
|
||||
return invoke<SaveProxyPortsOutcome>('save_proxy_ports', { settings })
|
||||
}
|
||||
|
||||
export interface UnlockItem {
|
||||
name: string
|
||||
status: string
|
||||
region?: string | null
|
||||
check_time?: string | null
|
||||
}
|
||||
|
||||
export async function getUnlockItems() {
|
||||
return invoke<UnlockItem[]>('get_unlock_items')
|
||||
}
|
||||
|
||||
export async function checkMediaUnlock(onComplete: Channel<UnlockItem>) {
|
||||
return invoke<UnlockItem[]>('check_media_unlock', { onComplete })
|
||||
}
|
||||
|
||||
export async function checkMediaUnlockItem(name: string) {
|
||||
return invoke<UnlockItem>('check_media_unlock_item', { name })
|
||||
}
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
// @generated by scripts/gen-contract.mjs from the backend wire contract. DO NOT EDIT.
|
||||
// Regen: pnpm gen:contract
|
||||
|
||||
import type { RunState } from './cmds'
|
||||
|
||||
/** Wire status strings from NoticeStatus; keep in sync via `pnpm gen:contract`. */
|
||||
export type NoticeStatus =
|
||||
| 'info'
|
||||
| 'import_sub_url::ok'
|
||||
| 'import_sub_url::error'
|
||||
| 'set_config::error'
|
||||
| 'core_start::error'
|
||||
| 'service_core::repair_required'
|
||||
| 'service_core::app_data_not_owned'
|
||||
| 'service_core::sidecar_fallback'
|
||||
| 'dns_override::auto_disabled'
|
||||
| 'enhance::discarded_keys'
|
||||
| 'tun_mode::auto_disabled'
|
||||
| 'tun_mode::auto_disable_failed'
|
||||
| 'app_restart::core_stop_failed'
|
||||
| 'app_quit::core_stop_failed'
|
||||
| 'update_with_clash_proxy'
|
||||
| 'update_failed_even_with_clash'
|
||||
| 'reactivate_profiles::error'
|
||||
| 'update_failed'
|
||||
| 'config_validate::boot_error'
|
||||
| 'config_validate::error'
|
||||
| 'config_validate::process_terminated'
|
||||
| 'config_validate::script_error'
|
||||
| 'config_validate::script_syntax_error'
|
||||
| 'config_validate::script_missing_main'
|
||||
| 'config_validate::file_not_found'
|
||||
| 'config_validate::yaml_syntax_error'
|
||||
| 'config_validate::yaml_read_error'
|
||||
| 'config_validate::yaml_mapping_error'
|
||||
| 'config_validate::merge_syntax_error'
|
||||
| 'config_validate::merge_mapping_error'
|
||||
| 'config_core::change_success'
|
||||
| 'config_core::change_error'
|
||||
| 'mixed_port::fallback'
|
||||
| 'mixed_port::fallback_error'
|
||||
|
||||
/** Event name → payload type for every backend-emitted event. */
|
||||
export interface VergeEventPayloads {
|
||||
'verge://refresh-clash-config': string
|
||||
'verge://refresh-verge-config': string
|
||||
'verge://refresh-profiles': string
|
||||
'verge://refresh-proxy-config': null
|
||||
'verge://notice-message': [NoticeStatus, string]
|
||||
'verge://timer-updated': string
|
||||
'verge://run-state-changed': RunState
|
||||
'verge://pending-failures-changed': null
|
||||
'profile-changed': string
|
||||
'profile-update-started': { uid: string }
|
||||
'profile-update-completed': { uid: string }
|
||||
}
|
||||
@@ -1,58 +0,0 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
import { subscribeVergeEvents } from './events'
|
||||
|
||||
const listen = vi.hoisted(() => vi.fn())
|
||||
|
||||
vi.mock('@tauri-apps/api/event', () => ({ listen }))
|
||||
|
||||
const flush = () => new Promise((resolve) => setTimeout(resolve, 0))
|
||||
|
||||
beforeEach(() => {
|
||||
listen.mockReset()
|
||||
})
|
||||
|
||||
describe('subscribeVergeEvents', () => {
|
||||
it('reports readiness only after every listener is registered', async () => {
|
||||
const registrations: Array<() => void> = []
|
||||
listen.mockImplementation(
|
||||
() =>
|
||||
new Promise((resolve) => {
|
||||
registrations.push(() => resolve(() => {}))
|
||||
}),
|
||||
)
|
||||
const onSubscribed = vi.fn()
|
||||
|
||||
subscribeVergeEvents(
|
||||
{
|
||||
'verge://run-state-changed': () => {},
|
||||
'verge://notice-message': () => {},
|
||||
},
|
||||
onSubscribed,
|
||||
)
|
||||
|
||||
registrations[0]?.()
|
||||
await flush()
|
||||
expect(onSubscribed).not.toHaveBeenCalled()
|
||||
|
||||
registrations[1]?.()
|
||||
await flush()
|
||||
expect(onSubscribed).toHaveBeenCalledOnce()
|
||||
})
|
||||
|
||||
it('delivers a payload to its matching handler', () => {
|
||||
const handlers = new Map<string, (payload: unknown) => void>()
|
||||
listen.mockImplementation(
|
||||
(name: string, handler: (event: unknown) => void) => {
|
||||
handlers.set(name, (payload) => handler({ payload }))
|
||||
return Promise.resolve(() => {})
|
||||
},
|
||||
)
|
||||
const onRunState = vi.fn()
|
||||
|
||||
subscribeVergeEvents({ 'verge://run-state-changed': onRunState })
|
||||
handlers.get('verge://run-state-changed')?.({ mode: 'Sidecar' })
|
||||
|
||||
expect(onRunState).toHaveBeenCalledWith({ mode: 'Sidecar' })
|
||||
})
|
||||
})
|
||||
@@ -1,75 +0,0 @@
|
||||
import { listen, type UnlistenFn } from '@tauri-apps/api/event'
|
||||
|
||||
import type { RunState } from './cmds'
|
||||
|
||||
/** Centralizes frontend event names and payload types for the unchecked Rust IPC seam. */
|
||||
interface VergeEvents {
|
||||
'verge://refresh-clash-config': string
|
||||
'verge://refresh-verge-config': string
|
||||
'verge://refresh-profiles': string
|
||||
'verge://refresh-proxy-config': null
|
||||
/** A backend message for the user: `[status, message]`. */
|
||||
'verge://notice-message': [string, string]
|
||||
'verge://timer-updated': string
|
||||
'verge://run-state-changed': RunState
|
||||
'verge://pending-failures-changed': null
|
||||
'profile-changed': string
|
||||
'profile-update-started': { uid?: string }
|
||||
'profile-update-completed': { uid?: string }
|
||||
'verge://test-all': null
|
||||
}
|
||||
|
||||
type VergeEventName = keyof VergeEvents
|
||||
|
||||
type VergeEventHandlers = {
|
||||
[Name in VergeEventName]?: (payload: VergeEvents[Name]) => void
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns synchronous teardown for asynchronous registrations. `onSubscribed` lets callers
|
||||
* reread event-only state after all listeners are live, closing the initial race window.
|
||||
*/
|
||||
export const subscribeVergeEvents = (
|
||||
handlers: VergeEventHandlers,
|
||||
onSubscribed?: () => void,
|
||||
): (() => void) => {
|
||||
let disposed = false
|
||||
const unlisteners: UnlistenFn[] = []
|
||||
|
||||
const registrations = Object.entries(handlers).map(([name, handler]) => {
|
||||
if (!handler) return Promise.resolve()
|
||||
|
||||
return listen(name, ({ payload }) => {
|
||||
;(handler as (payload: unknown) => void)(payload)
|
||||
})
|
||||
.then((unlisten) => {
|
||||
// Resolved after teardown: unsubscribe immediately rather than leak.
|
||||
if (disposed) {
|
||||
unlisten()
|
||||
return
|
||||
}
|
||||
unlisteners.push(unlisten)
|
||||
})
|
||||
.catch((error) => {
|
||||
console.error(`[events] failed to subscribe to ${name}:`, error)
|
||||
})
|
||||
})
|
||||
|
||||
if (onSubscribed) {
|
||||
void Promise.all(registrations).then(() => {
|
||||
if (disposed) return
|
||||
onSubscribed()
|
||||
})
|
||||
}
|
||||
|
||||
return () => {
|
||||
disposed = true
|
||||
for (const unlisten of unlisteners.splice(0)) {
|
||||
try {
|
||||
unlisten()
|
||||
} catch (error) {
|
||||
console.error('[events] teardown failed:', error)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
import { expect, it, vi } from 'vitest'
|
||||
|
||||
import { mutate } from './mutate'
|
||||
|
||||
vi.mock('@/services/notice-service', () => ({
|
||||
showNotice: { error: vi.fn(), warning: vi.fn(), success: vi.fn() },
|
||||
}))
|
||||
vi.mock('@/services/query-client', () => ({ revalidateQueries: vi.fn() }))
|
||||
|
||||
it('executes every queued setting write even when its predecessor fails', async () => {
|
||||
let reject!: (error: Error) => void
|
||||
const first = mutate(
|
||||
() =>
|
||||
new Promise<void>((_resolve, rejectFirst) => {
|
||||
reject = rejectFirst
|
||||
}),
|
||||
{ id: 'patch-verge-config', errorNotice: false },
|
||||
).catch((error) => error)
|
||||
const writeSecond = vi.fn().mockResolvedValue(undefined)
|
||||
const onFulfilled = vi.fn()
|
||||
const second = mutate(writeSecond, {
|
||||
id: 'patch-verge-config',
|
||||
onFulfilled,
|
||||
errorNotice: false,
|
||||
})
|
||||
expect(writeSecond).not.toHaveBeenCalled()
|
||||
const error = new Error('first write failed')
|
||||
reject(error)
|
||||
expect(await first).toBe(error)
|
||||
expect(await second).toEqual({ ok: true, value: undefined })
|
||||
expect(writeSecond).toHaveBeenCalledOnce()
|
||||
expect(onFulfilled).toHaveBeenCalledOnce()
|
||||
})
|
||||
@@ -0,0 +1,64 @@
|
||||
import { showNotice } from '@/services/notice-service'
|
||||
import { revalidateQueries } from '@/services/query-client'
|
||||
|
||||
/** Anything a notice call accepts: translation key, ReactNode, or failure payload. */
|
||||
type MutateNoticeInput = Parameters<typeof showNotice.error>[0]
|
||||
|
||||
export interface MutateOptions<T> {
|
||||
/** Commands with the same identity execute in request order. */
|
||||
id: string
|
||||
/** Runs after a fulfilled (non-busy) result, e.g. cache merges. */
|
||||
onFulfilled?: (value: T) => void
|
||||
/** SWR keys revalidated after a fulfilled result. */
|
||||
revalidate?: readonly (readonly unknown[] | string)[]
|
||||
/** Shown after a fulfilled result (most flows leave this to backend notices). */
|
||||
successNotice?: MutateNoticeInput
|
||||
/** `false` suppresses the default error toast. */
|
||||
errorNotice?: false
|
||||
}
|
||||
|
||||
export type MutateResult<T> = { ok: true; value: T } | { ok: false; value: T }
|
||||
|
||||
/** ValidationOutcome-shaped results report backend-side Busy rejection this way. */
|
||||
const isBusyOutcome = (value: unknown): boolean =>
|
||||
typeof value === 'object' &&
|
||||
value !== null &&
|
||||
(value as { status?: unknown }).status === 'busy'
|
||||
|
||||
const inFlight = new Map<string, Promise<void>>()
|
||||
export async function mutate<T>(
|
||||
invoke: () => Promise<T>,
|
||||
options: MutateOptions<T>,
|
||||
): Promise<MutateResult<T>> {
|
||||
const { id } = options
|
||||
const previous = inFlight.get(id)
|
||||
let release!: () => void
|
||||
const settled = new Promise<void>((resolve) => {
|
||||
release = resolve
|
||||
})
|
||||
inFlight.set(id, settled)
|
||||
if (previous) await previous
|
||||
|
||||
try {
|
||||
const value = await invoke()
|
||||
if (isBusyOutcome(value)) {
|
||||
return { ok: false, value }
|
||||
}
|
||||
options.onFulfilled?.(value)
|
||||
if (options.revalidate?.length) {
|
||||
await revalidateQueries([...options.revalidate])
|
||||
}
|
||||
if (options.successNotice !== undefined) {
|
||||
showNotice.success(options.successNotice)
|
||||
}
|
||||
return { ok: true, value }
|
||||
} catch (error) {
|
||||
if (options.errorNotice !== false) {
|
||||
showNotice.error(error)
|
||||
}
|
||||
throw error
|
||||
} finally {
|
||||
release()
|
||||
if (inFlight.get(id) === settled) inFlight.delete(id)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,262 @@
|
||||
import { getCurrentWindow } from '@tauri-apps/api/window'
|
||||
|
||||
import {
|
||||
getCoreStartupError,
|
||||
takeDiscardedKeysNotice,
|
||||
takeDnsOverrideNotice,
|
||||
takeServiceFallbackNotice,
|
||||
takeServiceOwnerNotice,
|
||||
takeServiceRepairNotice,
|
||||
} from '@/services/cmds'
|
||||
import type { NoticeStatus } from '@/services/contract'
|
||||
import { hideNotice, showNotice } from '@/services/notice-service'
|
||||
import { requestService } from '@/services/service-request'
|
||||
|
||||
type NavigateFunction = (path: string, options?: any) => void
|
||||
type TranslateFunction = (key: string) => string
|
||||
|
||||
let shownStartupError: string | null = null
|
||||
// Reads can settle out of order; only the newest may act, and a reset counts as one.
|
||||
let startupErrorReads = 0
|
||||
let settledStartupErrorRead = 0
|
||||
let shownOwnerNotice: number | null = null
|
||||
|
||||
/** A running core has resolved every failure shown before it. */
|
||||
export const forgetShownStartupError = () => {
|
||||
shownStartupError = null
|
||||
settledStartupErrorRead = ++startupErrorReads
|
||||
}
|
||||
|
||||
/**
|
||||
* Exhaustive notice table: one entry per contract `NoticeStatus`. The Record
|
||||
* type makes a backend status without a frontend entry a compile error (and
|
||||
* contract regeneration keeps the union in sync).
|
||||
*/
|
||||
export const handleNoticeMessage = (
|
||||
status: string,
|
||||
msg: string,
|
||||
t: TranslateFunction,
|
||||
navigate: NavigateFunction,
|
||||
) => {
|
||||
const handlers: Record<NoticeStatus, () => void> = {
|
||||
info: () => {
|
||||
if (msg) showNotice.info(msg)
|
||||
},
|
||||
'import_sub_url::ok': () => {
|
||||
// 空 msg 传入,我们不希望导致 后端-前端-后端 死循环,这里只做提醒。
|
||||
// 未来细分事件通知时,可以考虑传入订阅 ID 或其他标识符
|
||||
// navigate("/profile", { state: { current: msg } });
|
||||
navigate('/profile')
|
||||
showNotice.success(
|
||||
'shared.feedback.notifications.importSubscriptionSuccess',
|
||||
)
|
||||
},
|
||||
'import_sub_url::error': () => {
|
||||
navigate('/profile')
|
||||
showNotice.error(msg)
|
||||
},
|
||||
'set_config::error': () => showNotice.error(msg),
|
||||
'core_start::error': () => {
|
||||
const read = ++startupErrorReads
|
||||
void getCoreStartupError()
|
||||
.then(async (failure) => {
|
||||
if (read < settledStartupErrorRead) return
|
||||
settledStartupErrorRead = read
|
||||
if (!failure) {
|
||||
shownStartupError = null
|
||||
return
|
||||
}
|
||||
const window = getCurrentWindow()
|
||||
const [visible, minimized] = await Promise.all([
|
||||
window.isVisible(),
|
||||
window.isMinimized(),
|
||||
])
|
||||
const shown = `${failure.kind}:${failure.detail}`
|
||||
if (
|
||||
read === settledStartupErrorRead &&
|
||||
visible &&
|
||||
!minimized &&
|
||||
shownStartupError !== shown
|
||||
) {
|
||||
shownStartupError = shown
|
||||
showNotice.error(
|
||||
failure.kind === 'serviceCoreStopped'
|
||||
? 'settings.feedback.errors.clash.serviceCoreStopped'
|
||||
: 'settings.feedback.errors.clash.startFailed',
|
||||
failure.detail,
|
||||
)
|
||||
}
|
||||
})
|
||||
.catch((error) => {
|
||||
console.error('Failed to read the pending core startup error', error)
|
||||
})
|
||||
},
|
||||
'service_core::repair_required': () => {
|
||||
void takeServiceRepairNotice()
|
||||
.then((pending) => {
|
||||
if (pending) {
|
||||
requestService({ reason: 'serviceLocationRefused' })
|
||||
}
|
||||
})
|
||||
.catch((error) => {
|
||||
console.error(
|
||||
'Failed to read the pending service repair notice',
|
||||
error,
|
||||
)
|
||||
})
|
||||
},
|
||||
'service_core::app_data_not_owned': () => {
|
||||
void takeServiceOwnerNotice()
|
||||
.then((command) => {
|
||||
if (command) {
|
||||
if (shownOwnerNotice !== null) hideNotice(shownOwnerNotice)
|
||||
shownOwnerNotice = showNotice.warning(
|
||||
'settings.feedback.notifications.clashService.appDataNotOwned',
|
||||
{ command },
|
||||
0,
|
||||
)
|
||||
}
|
||||
})
|
||||
.catch((error) => {
|
||||
console.error(
|
||||
'Failed to read the pending service owner notice',
|
||||
error,
|
||||
)
|
||||
})
|
||||
},
|
||||
'service_core::sidecar_fallback': () => {
|
||||
void takeServiceFallbackNotice()
|
||||
.then((notice) => {
|
||||
if (notice?.kind === 'coreRejected') {
|
||||
showNotice.warning(
|
||||
'settings.feedback.notifications.clashService.permissionFallback',
|
||||
{ reason: notice.reason },
|
||||
0,
|
||||
)
|
||||
} else if (notice?.kind === 'notAutoStarted') {
|
||||
requestService({ reason: 'serviceNotAutoStarted' })
|
||||
} else if (notice) {
|
||||
showNotice.warning(
|
||||
'settings.feedback.notifications.clashService.sidecarFallback',
|
||||
)
|
||||
}
|
||||
})
|
||||
.catch((error) => {
|
||||
console.error(
|
||||
'Failed to read the pending service fallback notice',
|
||||
error,
|
||||
)
|
||||
})
|
||||
},
|
||||
'dns_override::auto_disabled': () => {
|
||||
void takeDnsOverrideNotice()
|
||||
.then((pending) => {
|
||||
if (pending) {
|
||||
showNotice.info('settings.modals.dns.protection.autoDisabled')
|
||||
}
|
||||
})
|
||||
.catch((error) => {
|
||||
console.error('Failed to read the pending DNS override notice', error)
|
||||
})
|
||||
},
|
||||
'enhance::discarded_keys': () => {
|
||||
void takeDiscardedKeysNotice()
|
||||
.then((keys) => {
|
||||
if (keys) {
|
||||
showNotice.warning('profiles.page.feedback.notices.discardedKeys', {
|
||||
keys,
|
||||
})
|
||||
}
|
||||
})
|
||||
.catch((error) => {
|
||||
console.error(
|
||||
'Failed to read the pending discarded keys notice',
|
||||
error,
|
||||
)
|
||||
})
|
||||
},
|
||||
'tun_mode::auto_disabled': () =>
|
||||
showNotice.info(
|
||||
'settings.sections.system.notifications.tunMode.autoDisabled',
|
||||
),
|
||||
'tun_mode::auto_disable_failed': () =>
|
||||
showNotice.error(
|
||||
'settings.sections.system.notifications.tunMode.autoDisableFailed',
|
||||
),
|
||||
'app_restart::core_stop_failed': () =>
|
||||
showNotice.error(
|
||||
'layout.feedback.errors.restartCoreStopFailed',
|
||||
msg || undefined,
|
||||
),
|
||||
'app_quit::core_stop_failed': () =>
|
||||
showNotice.error(
|
||||
'layout.feedback.errors.quitCoreStopFailed',
|
||||
msg || undefined,
|
||||
),
|
||||
update_with_clash_proxy: () =>
|
||||
showNotice.success(
|
||||
'settings.feedback.notifications.updater.withClashProxySuccess',
|
||||
msg,
|
||||
),
|
||||
update_failed_even_with_clash: () =>
|
||||
showNotice.error(
|
||||
'settings.feedback.notifications.updater.withClashProxyFailed',
|
||||
msg,
|
||||
),
|
||||
'reactivate_profiles::error': () => showNotice.error(msg),
|
||||
update_failed: () => showNotice.error(msg),
|
||||
'config_validate::boot_error': () =>
|
||||
showNotice.error('shared.feedback.validation.config.bootFailed', msg),
|
||||
'config_validate::error': () =>
|
||||
showNotice.error('shared.feedback.validation.config.failed', msg),
|
||||
'config_validate::process_terminated': () =>
|
||||
showNotice.error('shared.feedback.validation.config.processTerminated'),
|
||||
'config_validate::script_error': () =>
|
||||
showNotice.error('shared.feedback.validation.script.fileError', msg),
|
||||
'config_validate::script_syntax_error': () =>
|
||||
showNotice.error('shared.feedback.validation.script.syntaxError', msg),
|
||||
'config_validate::script_missing_main': () =>
|
||||
showNotice.error('shared.feedback.validation.script.missingMain', msg),
|
||||
'config_validate::file_not_found': () =>
|
||||
showNotice.error('shared.feedback.validation.script.fileNotFound', msg),
|
||||
'config_validate::yaml_syntax_error': () =>
|
||||
showNotice.error('shared.feedback.validation.yaml.syntaxError', msg),
|
||||
'config_validate::yaml_read_error': () =>
|
||||
showNotice.error('shared.feedback.validation.yaml.readError', msg),
|
||||
'config_validate::yaml_mapping_error': () =>
|
||||
showNotice.error('shared.feedback.validation.yaml.mappingError', msg),
|
||||
'config_validate::merge_syntax_error': () =>
|
||||
showNotice.error('shared.feedback.validation.merge.syntaxError', msg),
|
||||
'config_validate::merge_mapping_error': () =>
|
||||
showNotice.error('shared.feedback.validation.merge.mappingError', msg),
|
||||
'config_core::change_success': () =>
|
||||
showNotice.success(
|
||||
'settings.feedback.notifications.clash.changeSuccess',
|
||||
msg,
|
||||
),
|
||||
'config_core::change_error': () =>
|
||||
showNotice.error(
|
||||
'settings.feedback.notifications.clash.changeFailed',
|
||||
msg,
|
||||
),
|
||||
'mixed_port::fallback': () => {
|
||||
const [oldPort, newPort] = msg.split(',')
|
||||
showNotice.info('settings.modals.clashPort.messages.automaticFallback', {
|
||||
oldPort,
|
||||
newPort,
|
||||
})
|
||||
},
|
||||
'mixed_port::fallback_error': () =>
|
||||
showNotice.error(
|
||||
'settings.modals.clashPort.messages.automaticFallbackFailed',
|
||||
{ error: msg },
|
||||
),
|
||||
}
|
||||
|
||||
const handler = handlers[status as NoticeStatus]
|
||||
if (handler) {
|
||||
handler()
|
||||
} else {
|
||||
console.warn(`未处理的通知状态: ${status}`)
|
||||
}
|
||||
}
|
||||
@@ -4,10 +4,6 @@ const [ThemeModeProvider, useThemeMode, useSetThemeMode] = createContextState<
|
||||
'light' | 'dark'
|
||||
>()
|
||||
|
||||
// save the state of each profile item loading
|
||||
const [LoadingCacheProvider, useLoadingCache, useSetLoadingCache] =
|
||||
createContextState<Set<string>>(new Set())
|
||||
|
||||
// save update state
|
||||
const [UpdateStateProvider, useUpdateState, useSetUpdateState] =
|
||||
createContextState<boolean>(false)
|
||||
@@ -16,9 +12,6 @@ export {
|
||||
ThemeModeProvider,
|
||||
useThemeMode,
|
||||
useSetThemeMode,
|
||||
LoadingCacheProvider,
|
||||
useLoadingCache,
|
||||
useSetLoadingCache,
|
||||
UpdateStateProvider,
|
||||
useUpdateState,
|
||||
useSetUpdateState,
|
||||
|
||||
Reference in New Issue
Block a user