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:
Tunglies
2026-10-07 07:38:55 +00:00
committed by GitHub
parent 8328e34208
commit 69b76cc6a9
100 changed files with 2208 additions and 1127 deletions
+11 -5
View File
@@ -8,6 +8,7 @@ import {
getRuntimeConfig,
patchClashConfig,
} from '@/services/cmds'
import { mutate } from '@/services/mutate'
import {
revalidateQuery,
setCacheData,
@@ -104,8 +105,11 @@ export const useClash = () => {
}
const patchClash = useLockFn(async (patch: Partial<IConfigData>) => {
await patchClashConfig(patch)
mutateClash()
await mutate(() => patchClashConfig(patch), {
id: 'patch-clash-config',
revalidate: [['getRuntimeConfig']],
errorNotice: false,
})
})
const version = versionData?.meta
@@ -132,9 +136,11 @@ export const useClashInfo = () => {
validatePorts(patch)
await patchClashConfig(patch)
mutateInfo()
revalidateQuery(['getClashConfig'])
await mutate(() => patchClashConfig(patch), {
id: 'patch-clash-info',
revalidate: [['getClashInfo'], ['getClashConfig']],
errorNotice: false,
})
})
const invalidateClashConfig = () => revalidateQuery(['getClashConfig'])
-15
View File
@@ -1,15 +0,0 @@
import { listen, EventCallback } from '@tauri-apps/api/event'
import { useCallback } from 'react'
export const useListen = () => {
const addListener = useCallback(
async <T>(eventName: string, handler: EventCallback<T>) => {
return await listen(eventName, handler)
},
[],
)
return {
addListener,
}
}
+23 -16
View File
@@ -1,18 +1,12 @@
import { useCallback, useRef } from 'react'
import { getProfiles, patchProfile, patchProfilesConfig } from '@/services/cmds'
import {
fetchCacheData,
revalidateQuery,
setCacheData,
useQuery,
} from '@/services/query-client'
import { mutate } from '@/services/mutate'
import { fetchCacheData, setCacheData, useQuery } from '@/services/query-client'
import { debugLog } from '@/utils/debug'
const profilesQueryKey = ['getProfiles'] as const
export const revalidateProfiles = () => revalidateQuery(profilesQueryKey)
export const fetchProfilesIntoCache = () =>
fetchCacheData(profilesQueryKey, getProfiles)
@@ -49,16 +43,25 @@ export const useProfiles = () => {
const patchProfiles = useCallback(
async (value: Partial<IProfilesConfig>) => {
try {
const outcome = await patchProfilesConfig(value)
const result = await mutate(() => patchProfilesConfig(value), {
id: 'patch-profiles-config',
onFulfilled: (outcome) => {
if (outcome.status === 'valid') {
void setCacheData<IProfilesConfig>(profilesQueryKey, (current) =>
current ? { ...current, ...value } : current,
)
}
},
})
if (outcome.status === 'valid') {
await setCacheData<IProfilesConfig>(profilesQueryKey, (current) =>
current ? { ...current, ...value } : current,
)
} else if (outcome.status !== 'busy') {
if (!result.ok) {
// Backend Busy keeps local state untouched, as before.
return result.value
}
const outcome = result.value
if (outcome.status !== 'valid' && outcome.status !== 'busy') {
await mutateProfiles()
}
return outcome
} catch (error) {
await mutateProfiles()
@@ -71,7 +74,11 @@ export const useProfiles = () => {
const patchCurrent = useCallback(
async (value: Partial<IProfileItem>) => {
if (profiles?.current) {
await patchProfile(profiles.current, value)
const uid = profiles.current
await mutate(() => patchProfile(uid, value), {
id: `patch-profile:${uid}`,
errorNotice: false,
})
void mutateProfiles()
}
},
+51
View File
@@ -0,0 +1,51 @@
import { selectNodeForGroup } from 'tauri-plugin-mihomo-api'
import { expect, it, vi } from 'vitest'
import { useProxySelection } from './use-proxy-selection'
const record = vi.hoisted(() => vi.fn())
vi.mock('react', () => ({
useCallback: (callback: unknown) => callback,
useRef: (current: unknown) => ({ current }),
}))
vi.mock('@/hooks/use-record-selection', () => ({
useRecordSelection: () => record,
useForgetSelection: () => vi.fn(),
}))
vi.mock('@/hooks/use-verge', () => ({ useVerge: () => ({ verge: {} }) }))
vi.mock('tauri-plugin-mihomo-api', () => ({
selectNodeForGroup: vi.fn(),
unfixedProxy: vi.fn(),
}))
vi.mock('@/services/cmds', () => ({ syncTrayProxySelection: vi.fn() }))
vi.mock('@/services/notice-service', () => ({ showNotice: { error: vi.fn() } }))
vi.mock('@/services/query-client', () => ({ revalidateQueries: vi.fn() }))
it('applies and records independent group selections while another group is pending', async () => {
let finishFirst!: () => void
vi.mocked(selectNodeForGroup)
.mockImplementationOnce(
() =>
new Promise((resolve) => {
finishFirst = resolve
}),
)
.mockResolvedValueOnce(undefined)
const firstSuccess = vi.fn()
const secondSuccess = vi.fn()
const first = useProxySelection({ onSuccess: firstSuccess })
const second = useProxySelection({ onSuccess: secondSuccess })
first.changeProxy('Group A', 'Node A')
second.changeProxy('Group B', 'Node B')
await vi.waitFor(() =>
expect(record).toHaveBeenCalledWith('Group B', 'Node B'),
)
expect(selectNodeForGroup).toHaveBeenCalledTimes(2)
expect(firstSuccess).not.toHaveBeenCalled()
expect(secondSuccess).toHaveBeenCalledOnce()
finishFirst()
await vi.waitFor(() =>
expect(record).toHaveBeenCalledWith('Group A', 'Node A'),
)
expect(firstSuccess).toHaveBeenCalledOnce()
})
+13 -6
View File
@@ -12,6 +12,7 @@ import {
} from '@/hooks/use-record-selection'
import { useVerge } from '@/hooks/use-verge'
import { syncTrayProxySelection } from '@/services/cmds'
import { mutate } from '@/services/mutate'
import { debugLog } from '@/utils/debug'
// 缓存连接清理
@@ -58,7 +59,10 @@ export const useProxySelection = (options: ProxySelectionOptions = {}) => {
// 切换节点
const syncTraySelection = useCallback(() => {
syncTrayProxySelection().catch((error) => {
mutate(() => syncTrayProxySelection(), {
id: 'sync-tray-selection',
errorNotice: false,
}).catch((error) => {
console.error('[ProxySelection] 托盘状态同步失败:', error)
})
}, [])
@@ -74,11 +78,14 @@ export const useProxySelection = (options: ProxySelectionOptions = {}) => {
}
try {
if (isFixedProxy) {
await unfixedProxy(groupName)
} else {
await selectNodeForGroup(groupName, proxyName)
}
const result = await mutate(
() =>
isFixedProxy
? unfixedProxy(groupName)
: selectNodeForGroup(groupName, proxyName),
{ id: `select-proxy-node:${groupName}`, errorNotice: false },
)
if (!result.ok) return
onSuccess?.()
syncTraySelection()
if (isFixedProxy) {
+9 -2
View File
@@ -1,6 +1,7 @@
import { useCallback } from 'react'
import { forgetSelectedNode, recordSelectedNode } from '@/services/cmds'
import { mutate } from '@/services/mutate'
/**
* Persists every group selection because core-local state is not durable across all run modes.
@@ -9,7 +10,10 @@ import { forgetSelectedNode, recordSelectedNode } from '@/services/cmds'
export const useRecordSelection = () => {
return useCallback(async (groupName: string, proxyName: string) => {
try {
await recordSelectedNode(groupName, proxyName)
await mutate(() => recordSelectedNode(groupName, proxyName), {
id: `persist-selected-node:${groupName}`,
errorNotice: false,
})
} catch (error) {
console.error('[Selection] 保存代理选择失败:', error)
}
@@ -19,7 +23,10 @@ export const useRecordSelection = () => {
export const useForgetSelection = () => {
return useCallback(async (groupName: string) => {
try {
await forgetSelectedNode(groupName)
await mutate(() => forgetSelectedNode(groupName), {
id: `persist-selected-node:${groupName}`,
errorNotice: false,
})
} catch (error) {
console.error('[Selection] 清除代理选择失败:', error)
}
+15 -5
View File
@@ -1,6 +1,7 @@
import { useCallback } from 'react'
import { installService, restartCore } from '@/services/cmds'
import { mutate } from '@/services/mutate'
import { showNotice } from '@/services/notice-service'
const executeWithErrorHandling = async <T>(
@@ -23,14 +24,19 @@ const executeWithErrorHandling = async <T>(
export const useServiceInstaller = () => {
const installServiceAndRestartCore = useCallback(async () => {
const outcome = await executeWithErrorHandling(
() => installService(),
const installResult = await executeWithErrorHandling(
() =>
mutate(() => installService(), {
id: 'install-service',
errorNotice: false,
}),
'settings.statuses.clashService.installing',
)
if (outcome.status === 'sidecar') {
if (!installResult.ok) return
if (installResult.value.status === 'sidecar') {
showNotice.warning(
'settings.feedback.notifications.clashService.permissionFallback',
{ reason: outcome.reason },
{ reason: installResult.value.reason },
0,
)
return
@@ -40,7 +46,11 @@ export const useServiceInstaller = () => {
)
await executeWithErrorHandling(
() => restartCore(),
() =>
mutate(() => restartCore(), {
id: 'restart-core',
errorNotice: false,
}),
'settings.statuses.clash.restarting',
'settings.feedback.notifications.clash.restartSuccess',
)
+10 -4
View File
@@ -1,6 +1,7 @@
import { useCallback } from 'react'
import { uninstallService } from '@/services/cmds'
import { mutate } from '@/services/mutate'
import { showNotice } from '@/services/notice-service'
import { useSystemState } from './use-system-state'
@@ -12,10 +13,15 @@ export const useServiceUninstaller = () => {
let uninstallError: unknown
showNotice.info('settings.statuses.clashService.uninstalling')
try {
await uninstallService()
showNotice.success(
'settings.feedback.notifications.clashService.uninstallSuccess',
)
const result = await mutate(() => uninstallService(), {
id: 'uninstall-service',
errorNotice: false,
})
if (result.ok) {
showNotice.success(
'settings.feedback.notifications.clashService.uninstallSuccess',
)
}
} catch (error) {
uninstallError = error
}
+9 -2
View File
@@ -9,6 +9,7 @@ import {
getEmbeddedServerPort,
patchVergeConfig,
} from '@/services/cmds'
import { mutate } from '@/services/mutate'
import {
removeCacheData,
revalidateQueries,
@@ -64,10 +65,16 @@ export const useSystemProxyState = () => {
while (pendingRef.current !== null) {
const target = pendingRef.current
pendingRef.current = null
await patchVergeConfig({ enable_system_proxy: target })
await mutate(() => patchVergeConfig({ enable_system_proxy: target }), {
id: 'toggle-system-proxy',
errorNotice: false,
})
confirmed = target
if (!target && verge?.auto_close_connection) {
await closeAllConnections().catch(() => {})
await mutate(() => closeAllConnections(), {
id: 'close-all-connections',
errorNotice: false,
}).catch(() => {})
}
}
} catch (error) {
+7 -25
View File
@@ -1,14 +1,7 @@
import {
getAppUptime,
getRuntimeState,
type RunState,
type RunningMode,
} from '@/services/cmds'
import { getAppUptime, type RunState, type RunningMode } from '@/services/cmds'
import { useQuery } from '@/services/query-client'
import { useAppReads, useRunState } from '@/store/app-store-context'
import { useVisibility } from './use-visibility'
export const runStateQueryKey = ['getRuntimeState'] as const
const appUptimeQueryKey = ['appUptime'] as const
/** Fail closed until the first snapshot so TUN never flashes as available. */
@@ -27,20 +20,9 @@ const unknownRunState: RunState = {
/** Event-driven run state; Rust owns all derived availability decisions. */
export function useSystemState() {
const pageVisible = useVisibility()
const {
data: runState = unknownRunState,
refetch: mutateSystemState,
isLoading,
} = useQuery({
queryKey: runStateQueryKey,
queryFn: getRuntimeState,
// A safety net only; transitions normally arrive by event.
refetchInterval: pageVisible ? 30000 : false,
refetchOnWindowFocus: true,
refetchOnReconnect: true,
})
const { readRunState } = useAppReads()
const snapshot = useRunState()
const runState = snapshot ?? unknownRunState
return {
runState,
@@ -50,8 +32,8 @@ export function useSystemState() {
isServiceMode: runState.mode === 'Service',
isTunModeAvailable: runState.tunCapable,
serviceNeedsAttention: runState.serviceNeedsAttention,
mutateSystemState,
isLoading,
mutateSystemState: readRunState,
isLoading: snapshot == null,
}
}
+10 -7
View File
@@ -1,6 +1,7 @@
import { useCallback } from 'react'
import { getVergeConfig, patchVergeConfig } from '@/services/cmds'
import { mutate } from '@/services/mutate'
import { getPreloadConfig, setPreloadConfig } from '@/services/preload'
import { setCacheData, useQuery } from '@/services/query-client'
@@ -38,13 +39,15 @@ export const useVerge = () => {
)
}
const patchVerge = useCallback(
async (value: Partial<IVergeConfig>) => {
await patchVergeConfig(value)
await refetch()
},
[refetch],
)
// Callers own the error toast (GuardState onCatch / page onError), so the
// funnel must not add a second one.
const patchVerge = useCallback(async (value: Partial<IVergeConfig>) => {
await mutate(() => patchVergeConfig(value), {
id: 'patch-verge-config',
revalidate: [['getVergeConfig']],
errorNotice: false,
})
}, [])
return {
verge,
+4 -8
View File
@@ -1,4 +1,3 @@
import { TauriEvent } from '@tauri-apps/api/event'
import { getCurrentWindow } from '@tauri-apps/api/window'
import { useEffect, useState } from 'react'
@@ -42,13 +41,10 @@ export const useVisibility = () => {
window.addEventListener('focus', handleVisibleEvent)
const unlistenFocusChanged = appWindow.onFocusChanged(updateVisibleSoon)
const unlistenCloseRequested = appWindow.listen(
TauriEvent.WINDOW_CLOSE_REQUESTED,
() => {
setVisible(false)
updateVisibleSoon()
},
)
const unlistenCloseRequested = appWindow.onCloseRequested(() => {
setVisible(false)
updateVisibleSoon()
})
void updateVisible()
return () => {