fix: handle core state errors caused by rapid profile switching

This commit is contained in:
ezequielnick 2025-09-09 17:00:04 +08:00
parent e075bd5d8c
commit 4137f91ccb
7 changed files with 82 additions and 31 deletions

View File

@ -13,6 +13,8 @@ import { join } from 'path'
import { app } from 'electron' import { app } from 'electron'
let profileConfig: IProfileConfig // profile.yaml let profileConfig: IProfileConfig // profile.yaml
// 最终选中订阅ID
let targetProfileId: string | null = null
export async function getProfileConfig(force = false): Promise<IProfileConfig> { export async function getProfileConfig(force = false): Promise<IProfileConfig> {
if (force || !profileConfig) { if (force || !profileConfig) {
@ -38,20 +40,33 @@ export async function changeCurrentProfile(id: string): Promise<void> {
const config = await getProfileConfig() const config = await getProfileConfig()
const current = config.current const current = config.current
if (current === id) { if (current === id && targetProfileId !== id) {
return return
} }
targetProfileId = id
config.current = id config.current = id
await setProfileConfig(config) const configSavePromise = setProfileConfig(config)
try { try {
await configSavePromise
// 检查订阅切换是否中断
if (targetProfileId !== id) {
return
}
await restartCore() await restartCore()
if (targetProfileId === id) {
targetProfileId = null
}
} catch (e) { } catch (e) {
// 如果重启失败,恢复原来的配置 if (targetProfileId === id) {
config.current = current config.current = current
await setProfileConfig(config) await setProfileConfig(config)
throw e targetProfileId = null
throw e
}
} }
} }
@ -203,7 +218,8 @@ export async function getProfileStr(id: string | undefined): Promise<string> {
} }
export async function setProfileStr(id: string, content: string): Promise<void> { export async function setProfileStr(id: string, content: string): Promise<void> {
const { current } = await getProfileConfig() // 读取最新的配置
const { current } = await getProfileConfig(true)
await writeFile(profilePath(id), content, 'utf-8') await writeFile(profilePath(id), content, 'utf-8')
if (current === id) await restartCore() if (current === id) await restartCore()
} }

View File

@ -25,7 +25,8 @@ let runtimeConfigStr: string
let runtimeConfig: IMihomoConfig let runtimeConfig: IMihomoConfig
export async function generateProfile(): Promise<void> { export async function generateProfile(): Promise<void> {
const { current } = await getProfileConfig() // 读取最新的配置
const { current } = await getProfileConfig(true)
const { diffWorkDir = false, controlDns = true, controlSniff = true, useNameserverPolicy } = await getAppConfig() const { diffWorkDir = false, controlDns = true, controlSniff = true, useNameserverPolicy } = await getAppConfig()
const currentProfile = await overrideProfile(current, await getProfile(current)) const currentProfile = await overrideProfile(current, await getProfile(current))
let controledMihomoConfig = await getControledMihomoConfig() let controledMihomoConfig = await getControledMihomoConfig()

View File

@ -79,6 +79,7 @@ let setPublicDNSTimer: NodeJS.Timeout | null = null
let recoverDNSTimer: NodeJS.Timeout | null = null let recoverDNSTimer: NodeJS.Timeout | null = null
let child: ChildProcess let child: ChildProcess
let retry = 10 let retry = 10
let isRestarting = false
export async function startCore(detached = false): Promise<Promise<void>[]> { export async function startCore(detached = false): Promise<Promise<void>[]> {
const { const {
@ -102,7 +103,7 @@ export async function startCore(detached = false): Promise<Promise<void>[]> {
await rm(path.join(dataDir(), 'core.pid')) await rm(path.join(dataDir(), 'core.pid'))
} }
} }
const { current } = await getProfileConfig() const { current } = await getProfileConfig(true)
const { tun } = await getControledMihomoConfig() const { tun } = await getControledMihomoConfig()
const corePath = mihomoCorePath(core) const corePath = mihomoCorePath(core)
@ -161,6 +162,12 @@ export async function startCore(detached = false): Promise<Promise<void>[]> {
} }
child.on('close', async (code, signal) => { child.on('close', async (code, signal) => {
await managerLogger.info(`Core closed, code: ${code}, signal: ${signal}`) await managerLogger.info(`Core closed, code: ${code}, signal: ${signal}`)
if (isRestarting) {
await managerLogger.info('Core closed during restart, skipping auto-restart')
return
}
if (retry) { if (retry) {
await managerLogger.info('Try Restart Core') await managerLogger.info('Try Restart Core')
retry-- retry--
@ -293,10 +300,14 @@ async function cleanupWindowsNamedPipes(): Promise<void> {
const pid = proc.Id const pid = proc.Id
if (pid && pid !== process.pid) { if (pid && pid !== process.pid) {
try { try {
// 先检查进程是否存在
process.kill(pid, 0)
process.kill(pid, 'SIGTERM') process.kill(pid, 'SIGTERM')
await managerLogger.info(`Terminated process ${pid} to free pipe`) await managerLogger.info(`Terminated process ${pid} to free pipe`)
} catch (error) { } catch (error: any) {
await managerLogger.warn(`Failed to terminate process ${pid}:`, error) if (error.code !== 'ESRCH') {
await managerLogger.warn(`Failed to terminate process ${pid}:`, error)
}
} }
} }
} }
@ -311,10 +322,13 @@ async function cleanupWindowsNamedPipes(): Promise<void> {
const pid = parseInt(match[1]) const pid = parseInt(match[1])
if (pid !== process.pid) { if (pid !== process.pid) {
try { try {
process.kill(pid, 0)
process.kill(pid, 'SIGTERM') process.kill(pid, 'SIGTERM')
await managerLogger.info(`Terminated process ${pid} to free pipe`) await managerLogger.info(`Terminated process ${pid} to free pipe`)
} catch (error) { } catch (error: any) {
await managerLogger.warn(`Failed to terminate process ${pid}:`, error) if (error.code !== 'ESRCH') {
await managerLogger.warn(`Failed to terminate process ${pid}:`, error)
}
} }
} }
} }
@ -367,13 +381,20 @@ async function validateWindowsPipeAccess(pipePath: string): Promise<void> {
} }
export async function restartCore(): Promise<void> { export async function restartCore(): Promise<void> {
// 防止并发重启
if (isRestarting) {
await managerLogger.info('Core restart already in progress, skipping duplicate request')
return
}
isRestarting = true
try { try {
await startCore() await startCore()
} catch (e) { } catch (e) {
// 记录错误到日志而不是显示阻塞对话框
await managerLogger.error('restart core failed', e) await managerLogger.error('restart core failed', e)
// 重新抛出错误,让调用者处理
throw e throw e
} finally {
isRestarting = false
} }
} }

View File

@ -205,6 +205,8 @@ export const startMihomoTraffic = async (): Promise<void> => {
} }
export const stopMihomoTraffic = (): void => { export const stopMihomoTraffic = (): void => {
trafficRetry = 0
if (mihomoTrafficWs) { if (mihomoTrafficWs) {
mihomoTrafficWs.removeAllListeners() mihomoTrafficWs.removeAllListeners()
if (mihomoTrafficWs.readyState === WebSocket.OPEN) { if (mihomoTrafficWs.readyState === WebSocket.OPEN) {
@ -262,6 +264,8 @@ export const startMihomoMemory = async (): Promise<void> => {
} }
export const stopMihomoMemory = (): void => { export const stopMihomoMemory = (): void => {
memoryRetry = 0
if (mihomoMemoryWs) { if (mihomoMemoryWs) {
mihomoMemoryWs.removeAllListeners() mihomoMemoryWs.removeAllListeners()
if (mihomoMemoryWs.readyState === WebSocket.OPEN) { if (mihomoMemoryWs.readyState === WebSocket.OPEN) {
@ -306,6 +310,8 @@ export const startMihomoLogs = async (): Promise<void> => {
} }
export const stopMihomoLogs = (): void => { export const stopMihomoLogs = (): void => {
logsRetry = 0
if (mihomoLogsWs) { if (mihomoLogsWs) {
mihomoLogsWs.removeAllListeners() mihomoLogsWs.removeAllListeners()
if (mihomoLogsWs.readyState === WebSocket.OPEN) { if (mihomoLogsWs.readyState === WebSocket.OPEN) {
@ -352,6 +358,8 @@ export const startMihomoConnections = async (): Promise<void> => {
} }
export const stopMihomoConnections = (): void => { export const stopMihomoConnections = (): void => {
connectionsRetry = 0
if (mihomoConnectionsWs) { if (mihomoConnectionsWs) {
mihomoConnectionsWs.removeAllListeners() mihomoConnectionsWs.removeAllListeners()
if (mihomoConnectionsWs.readyState === WebSocket.OPEN) { if (mihomoConnectionsWs.readyState === WebSocket.OPEN) {

View File

@ -57,7 +57,6 @@ const ProfileItem: React.FC<Props> = (props) => {
const { appConfig, patchAppConfig } = useAppConfig() const { appConfig, patchAppConfig } = useAppConfig()
const { profileDisplayDate = 'expire' } = appConfig || {} const { profileDisplayDate = 'expire' } = appConfig || {}
const [updating, setUpdating] = useState(false) const [updating, setUpdating] = useState(false)
const [selecting, setSelecting] = useState(false)
const [openInfoEditor, setOpenInfoEditor] = useState(false) const [openInfoEditor, setOpenInfoEditor] = useState(false)
const [openFileEditor, setOpenFileEditor] = useState(false) const [openFileEditor, setOpenFileEditor] = useState(false)
const [dropdownOpen, setDropdownOpen] = useState(false) const [dropdownOpen, setDropdownOpen] = useState(false)
@ -185,8 +184,7 @@ const ProfileItem: React.FC<Props> = (props) => {
// 处理卡片选中 // 处理卡片选中
if (!isActuallyDragging && !isDragging && clickStartPos) { if (!isActuallyDragging && !isDragging && clickStartPos) {
setSelecting(true) onPress()
onPress().finally(() => setSelecting(false))
} }
cleanup() cleanup()
@ -216,7 +214,7 @@ const ProfileItem: React.FC<Props> = (props) => {
fullWidth fullWidth
isPressable={false} isPressable={false}
onContextMenu={handleContextMenu} onContextMenu={handleContextMenu}
className={`${isCurrent ? 'bg-primary' : ''} ${selecting ? 'blur-sm' : ''} cursor-pointer`} className={`${isCurrent ? 'bg-primary' : ''} cursor-pointer transition-colors duration-150`}
> >
<div <div
ref={setNodeRef} ref={setNodeRef}

View File

@ -103,7 +103,7 @@ const ProfileCard: React.FC<Props> = (props) => {
> >
<h3 <h3
title={info?.name} title={info?.name}
className={`text-ellipsis whitespace-nowrap overflow-hidden text-md font-bold leading-[32px] ${match ? 'text-primary-foreground' : 'text-foreground'} `} className={`text-ellipsis whitespace-nowrap overflow-hidden text-md font-bold leading-[32px] ${match ? 'text-primary-foreground' : 'text-foreground'}`}
> >
{info?.name} {info?.name}
</h3> </h3>

View File

@ -25,6 +25,7 @@ export const ProfileConfigProvider: React.FC<{ children: ReactNode }> = ({ child
const { data: profileConfig, mutate: mutateProfileConfig } = useSWR('getProfileConfig', () => const { data: profileConfig, mutate: mutateProfileConfig } = useSWR('getProfileConfig', () =>
getProfileConfig() getProfileConfig()
) )
const [targetProfileId, setTargetProfileId] = React.useState<string | null>(null)
const setProfileConfig = async (config: IProfileConfig): Promise<void> => { const setProfileConfig = async (config: IProfileConfig): Promise<void> => {
try { try {
@ -71,23 +72,31 @@ export const ProfileConfigProvider: React.FC<{ children: ReactNode }> = ({ child
} }
const changeCurrentProfile = async (id: string): Promise<void> => { const changeCurrentProfile = async (id: string): Promise<void> => {
if (profileConfig?.current === id) { if (targetProfileId === id) {
return return
} }
// 乐观更新:立即更新 UI 状态,提供即时反馈 setTargetProfileId(id)
// 立即更新 UI 状态和托盘菜单,提供即时反馈
if (profileConfig) { if (profileConfig) {
const optimisticUpdate = { ...profileConfig, current: id } const optimisticUpdate = { ...profileConfig, current: id }
mutateProfileConfig(optimisticUpdate, false) mutateProfileConfig(optimisticUpdate, false)
window.electron.ipcRenderer.send('updateTrayMenu')
} }
// 异步执行后台切换,不阻塞 UI
try { try {
// 异步执行后台切换,不阻塞 UI await change(id)
change(id).then(() => {
window.electron.ipcRenderer.send('updateTrayMenu') if (targetProfileId === id) {
mutateProfileConfig() mutateProfileConfig()
}).catch((e) => { setTargetProfileId(null)
const errorMsg = e?.message || String(e) } else {
}
} catch (e) {
if (targetProfileId === id) {
const errorMsg = (e as any)?.message || String(e)
// 处理 IPC 超时错误 // 处理 IPC 超时错误
if (errorMsg.includes('reply was never sent')) { if (errorMsg.includes('reply was never sent')) {
setTimeout(() => mutateProfileConfig(), 1000) setTimeout(() => mutateProfileConfig(), 1000)
@ -95,10 +104,8 @@ export const ProfileConfigProvider: React.FC<{ children: ReactNode }> = ({ child
alert(`切换 Profile 失败: ${errorMsg}`) alert(`切换 Profile 失败: ${errorMsg}`)
mutateProfileConfig() mutateProfileConfig()
} }
}) setTargetProfileId(null)
} catch (e) { }
alert(`切换 Profile 失败: ${e}`)
mutateProfileConfig()
} }
} }