mirror of
https://github.com/clash-verge-rev/clash-verge-rev.git
synced 2026-10-28 00:42:08 +08:00
feat: allow manually unfixing proxy nodes (#7756)
* feat(proxy): add ability to clear persisted node selection for groups * feat(hooks): make proxy selection operations asynchronous * chore: update tauri-plugin-mihomo deps * refactor: rename clear_selected_node to forget_selected_node * refactor(hooks): rename isFixed to isFixedProxy in useProxySelection * docs: update changelog with manual node cancellation support * chore(layout): remove dev-only mihomo websocket debugging interval
This commit is contained in:
@@ -623,6 +623,7 @@ export const CurrentProxyCard = () => {
|
||||
handleSelectChange(
|
||||
selectedGroup.name,
|
||||
previousProxy,
|
||||
selectedGroup.fixed,
|
||||
)({
|
||||
target: { value: nextName },
|
||||
})
|
||||
|
||||
@@ -1,11 +1,15 @@
|
||||
import { useCallback, useMemo, useRef } from 'react'
|
||||
import { useCallback, useRef } from 'react'
|
||||
import {
|
||||
closeConnection,
|
||||
getConnections,
|
||||
selectNodeForGroup,
|
||||
unfixedProxy,
|
||||
} from 'tauri-plugin-mihomo-api'
|
||||
|
||||
import { useRecordSelection } from '@/hooks/use-record-selection'
|
||||
import {
|
||||
useForgetSelection,
|
||||
useRecordSelection,
|
||||
} from '@/hooks/use-record-selection'
|
||||
import { useVerge } from '@/hooks/use-verge'
|
||||
import { syncTrayProxySelection } from '@/services/cmds'
|
||||
import { debugLog } from '@/utils/debug'
|
||||
@@ -37,25 +41,20 @@ interface ProxyChangeRequest {
|
||||
groupName: string
|
||||
proxyName: string
|
||||
previousProxy?: string
|
||||
fixed?: string
|
||||
}
|
||||
|
||||
// 代理选择 Hook
|
||||
export const useProxySelection = (options: ProxySelectionOptions = {}) => {
|
||||
const recordSelection = useRecordSelection()
|
||||
const forgetSelection = useForgetSelection()
|
||||
const { verge } = useVerge()
|
||||
const pendingRequestRef = useRef<ProxyChangeRequest | null>(null)
|
||||
const isProcessingRef = useRef(false)
|
||||
|
||||
const { onSuccess, onError, enableConnectionCleanup = true } = options
|
||||
|
||||
// 缓存
|
||||
const config = useMemo(
|
||||
() => ({
|
||||
autoCloseConnection: verge?.auto_close_connection ?? false,
|
||||
enableConnectionCleanup,
|
||||
}),
|
||||
[verge?.auto_close_connection, enableConnectionCleanup],
|
||||
)
|
||||
const autoCloseConnection = verge?.auto_close_connection ?? false
|
||||
|
||||
// 切换节点
|
||||
const syncTraySelection = useCallback(() => {
|
||||
@@ -66,23 +65,33 @@ export const useProxySelection = (options: ProxySelectionOptions = {}) => {
|
||||
|
||||
const executeChange = useCallback(
|
||||
async (request: ProxyChangeRequest) => {
|
||||
const { groupName, proxyName, previousProxy } = request
|
||||
debugLog(`[ProxySelection] 代理切换: ${groupName} -> ${proxyName}`)
|
||||
const { groupName, proxyName, previousProxy, fixed } = request
|
||||
const isFixedProxy = fixed === proxyName
|
||||
if (isFixedProxy) {
|
||||
debugLog(`[ProxySelection] 代理取消固定: ${groupName} -> ${proxyName}`)
|
||||
} else {
|
||||
debugLog(`[ProxySelection] 代理切换: ${groupName} -> ${proxyName}`)
|
||||
}
|
||||
|
||||
try {
|
||||
await selectNodeForGroup(groupName, proxyName)
|
||||
if (isFixedProxy) {
|
||||
await unfixedProxy(groupName)
|
||||
} else {
|
||||
await selectNodeForGroup(groupName, proxyName)
|
||||
}
|
||||
onSuccess?.()
|
||||
syncTraySelection()
|
||||
recordSelection(groupName, proxyName)
|
||||
debugLog(
|
||||
`[ProxySelection] 代理和状态同步完成: ${groupName} -> ${proxyName}`,
|
||||
)
|
||||
if (isFixedProxy) {
|
||||
await forgetSelection(groupName)
|
||||
debugLog(`[ProxySelection] 代理和状态同步完成: ${groupName}`)
|
||||
} else {
|
||||
await recordSelection(groupName, proxyName)
|
||||
debugLog(
|
||||
`[ProxySelection] 代理和状态同步完成: ${groupName} -> ${proxyName}`,
|
||||
)
|
||||
}
|
||||
|
||||
if (
|
||||
config.enableConnectionCleanup &&
|
||||
config.autoCloseConnection &&
|
||||
previousProxy
|
||||
) {
|
||||
if (enableConnectionCleanup && autoCloseConnection && previousProxy) {
|
||||
void cleanupConnections(previousProxy)
|
||||
}
|
||||
} catch (error) {
|
||||
@@ -93,7 +102,15 @@ export const useProxySelection = (options: ProxySelectionOptions = {}) => {
|
||||
onError?.(error)
|
||||
}
|
||||
},
|
||||
[config, onError, onSuccess, recordSelection, syncTraySelection],
|
||||
[
|
||||
autoCloseConnection,
|
||||
forgetSelection,
|
||||
enableConnectionCleanup,
|
||||
onError,
|
||||
onSuccess,
|
||||
recordSelection,
|
||||
syncTraySelection,
|
||||
],
|
||||
)
|
||||
|
||||
const flushChangeQueue = useCallback(async () => {
|
||||
@@ -115,11 +132,17 @@ export const useProxySelection = (options: ProxySelectionOptions = {}) => {
|
||||
}, [executeChange])
|
||||
|
||||
const changeProxy = useCallback(
|
||||
(groupName: string, proxyName: string, previousProxy?: string) => {
|
||||
(
|
||||
groupName: string,
|
||||
proxyName: string,
|
||||
previousProxy?: string,
|
||||
fixed?: string,
|
||||
) => {
|
||||
pendingRequestRef.current = {
|
||||
groupName,
|
||||
proxyName,
|
||||
previousProxy,
|
||||
fixed,
|
||||
}
|
||||
void flushChangeQueue()
|
||||
},
|
||||
@@ -127,17 +150,19 @@ export const useProxySelection = (options: ProxySelectionOptions = {}) => {
|
||||
)
|
||||
|
||||
const handleSelectChange = useCallback(
|
||||
(groupName: string, previousProxy?: string) =>
|
||||
(groupName: string, previousProxy?: string, fixed?: string) =>
|
||||
(event: { target: { value: string } }) => {
|
||||
const newProxy = event.target.value
|
||||
changeProxy(groupName, newProxy, previousProxy)
|
||||
changeProxy(groupName, event.target.value, previousProxy, fixed)
|
||||
},
|
||||
[changeProxy],
|
||||
)
|
||||
|
||||
const handleProxyGroupChange = useCallback(
|
||||
(group: { name: string; now?: string }, proxy: { name: string }) => {
|
||||
changeProxy(group.name, proxy.name, group.now)
|
||||
(
|
||||
group: { name: string; now?: string; fixed?: string },
|
||||
proxy: { name: string },
|
||||
) => {
|
||||
changeProxy(group.name, proxy.name, group.now, group.fixed)
|
||||
},
|
||||
[changeProxy],
|
||||
)
|
||||
|
||||
@@ -2,11 +2,12 @@
|
||||
import { renderHook } from '@testing-library/react'
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
import { useRecordSelection } from './use-record-selection'
|
||||
import { useForgetSelection, useRecordSelection } from './use-record-selection'
|
||||
|
||||
const recordSelectedNode = vi.hoisted(() => vi.fn(() => Promise.resolve()))
|
||||
const forgetSelectedNode = vi.hoisted(() => vi.fn(() => Promise.resolve()))
|
||||
|
||||
vi.mock('@/services/cmds', () => ({ recordSelectedNode }))
|
||||
vi.mock('@/services/cmds', () => ({ forgetSelectedNode, recordSelectedNode }))
|
||||
|
||||
const record = (groupName: string, proxyName: string) => {
|
||||
const { result } = renderHook(() => useRecordSelection())
|
||||
@@ -15,6 +16,49 @@ const record = (groupName: string, proxyName: string) => {
|
||||
|
||||
beforeEach(() => {
|
||||
recordSelectedNode.mockClear()
|
||||
forgetSelectedNode.mockClear()
|
||||
})
|
||||
|
||||
describe('useForgetSelection', () => {
|
||||
it('sends only the group name', () => {
|
||||
const { result } = renderHook(() => useForgetSelection())
|
||||
|
||||
result.current('Proxy')
|
||||
|
||||
expect(forgetSelectedNode).toHaveBeenCalledWith('Proxy')
|
||||
})
|
||||
|
||||
it('resolves after the clear request finishes', async () => {
|
||||
let resolveForget!: () => void
|
||||
forgetSelectedNode.mockImplementationOnce(
|
||||
() => new Promise<void>((resolve) => (resolveForget = resolve)),
|
||||
)
|
||||
const { result } = renderHook(() => useForgetSelection())
|
||||
|
||||
const forget = result.current('Proxy')
|
||||
let settled = false
|
||||
forget.then(() => {
|
||||
settled = true
|
||||
})
|
||||
|
||||
await Promise.resolve()
|
||||
expect(settled).toBe(false)
|
||||
|
||||
resolveForget()
|
||||
await forget
|
||||
expect(settled).toBe(true)
|
||||
})
|
||||
|
||||
it('reports a failed clear without throwing at the caller', async () => {
|
||||
const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {})
|
||||
forgetSelectedNode.mockRejectedValueOnce(new Error('no profile'))
|
||||
const { result } = renderHook(() => useForgetSelection())
|
||||
|
||||
expect(() => result.current('Proxy')).not.toThrow()
|
||||
|
||||
await vi.waitFor(() => expect(consoleError).toHaveBeenCalled())
|
||||
consoleError.mockRestore()
|
||||
})
|
||||
})
|
||||
|
||||
describe('useRecordSelection', () => {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { useCallback } from 'react'
|
||||
|
||||
import { recordSelectedNode } from '@/services/cmds'
|
||||
import { forgetSelectedNode, recordSelectedNode } from '@/services/cmds'
|
||||
|
||||
/**
|
||||
* Record which node a group is on, in the profile.
|
||||
@@ -20,9 +20,24 @@ import { recordSelectedNode } from '@/services/cmds'
|
||||
* stale snapshot. The merge happens on the backend, against whatever the profile holds by then.
|
||||
*/
|
||||
export const useRecordSelection = () => {
|
||||
return useCallback((groupName: string, proxyName: string) => {
|
||||
recordSelectedNode(groupName, proxyName).catch((error) => {
|
||||
return useCallback(async (groupName: string, proxyName: string) => {
|
||||
try {
|
||||
await recordSelectedNode(groupName, proxyName)
|
||||
} catch (error) {
|
||||
console.error('[Selection] 保存代理选择失败:', error)
|
||||
})
|
||||
}
|
||||
}, [])
|
||||
}
|
||||
|
||||
/**
|
||||
* Forget the persisted node selection for a group after its runtime fixed node is released.
|
||||
*/
|
||||
export const useForgetSelection = () => {
|
||||
return useCallback(async (groupName: string) => {
|
||||
try {
|
||||
await forgetSelectedNode(groupName)
|
||||
} catch (error) {
|
||||
console.error('[Selection] 清除代理选择失败:', error)
|
||||
}
|
||||
}, [])
|
||||
}
|
||||
|
||||
@@ -27,7 +27,6 @@ import type { CSSProperties } from 'react'
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { Outlet, useNavigate } from 'react-router'
|
||||
import { MihomoWebSocket } from 'tauri-plugin-mihomo-api'
|
||||
|
||||
import iconDark from '@/assets/image/icon_dark.svg?react'
|
||||
import iconLight from '@/assets/image/icon_light.svg?react'
|
||||
@@ -125,24 +124,6 @@ const Layout = () => {
|
||||
const navigate = useNavigate()
|
||||
const themeReady = useMemo(() => Boolean(theme), [theme])
|
||||
|
||||
// 开发环境下检测 MihomoWebSocket 的所有实例
|
||||
useEffect(() => {
|
||||
let id: number
|
||||
if (import.meta.env.DEV) {
|
||||
id = setInterval(() => {
|
||||
MihomoWebSocket.get_all_instances().then((list) => {
|
||||
console.log('Mihomo ws instances', list)
|
||||
})
|
||||
}, 1000)
|
||||
}
|
||||
|
||||
return () => {
|
||||
if (id) {
|
||||
clearInterval(id)
|
||||
}
|
||||
}
|
||||
}, [])
|
||||
|
||||
const [menuUnlocked, setMenuUnlocked] = useState(false)
|
||||
const [menuContextPosition, setMenuContextPosition] =
|
||||
useState<MenuContextPosition | null>(null)
|
||||
|
||||
@@ -136,6 +136,11 @@ export async function recordSelectedNode(groupName: string, node: string) {
|
||||
return invoke<void>('record_selected_node', { groupName, node })
|
||||
}
|
||||
|
||||
/** Forget the persisted node selection for one proxy group in the current profile. */
|
||||
export async function forgetSelectedNode(groupName: string) {
|
||||
return invoke<void>('forget_selected_node', { groupName })
|
||||
}
|
||||
|
||||
export async function getProxyView(): Promise<ProxyViewV1> {
|
||||
const view = await invoke<ProxyViewV1>('get_proxy_view')
|
||||
if (view.schemaVersion !== 1) {
|
||||
|
||||
Reference in New Issue
Block a user