feat: 添加代理会话初始化钩子并在相关组件中使用

This commit is contained in:
suyao 2025-09-23 05:19:00 +08:00
parent 56dbe6b050
commit ae1839ac33
No known key found for this signature in database
3 changed files with 93 additions and 6 deletions

View File

@ -0,0 +1,80 @@
import { loggerService } from '@logger'
import { useRuntime } from '@renderer/hooks/useRuntime'
import { useAppDispatch } from '@renderer/store'
import { setActiveSessionIdAction, setActiveTopicOrSessionAction } from '@renderer/store/runtime'
import { useCallback, useEffect } from 'react'
import { useAgentClient } from './useAgentClient'
const logger = loggerService.withContext('useAgentSessionInitializer')
/**
* Hook to automatically initialize and load the latest session for an agent
* when the agent is activated. This ensures that when switching to an agent,
* its most recent session is automatically selected.
*/
export const useAgentSessionInitializer = () => {
const dispatch = useAppDispatch()
const client = useAgentClient()
const { chat } = useRuntime()
const { activeAgentId, activeSessionId } = chat
/**
* Initialize session for the given agent by loading its sessions
* and setting the latest one as active
*/
const initializeAgentSession = useCallback(
async (agentId: string) => {
if (!agentId || agentId === 'fake') return
try {
// Check if this agent already has an active session
const currentSessionId = activeSessionId[agentId]
if (currentSessionId) {
// Session already exists, just switch to session view
dispatch(setActiveTopicOrSessionAction('session'))
return
}
// Load sessions for this agent
const response = await client.listSessions(agentId)
const sessions = response.data
if (sessions && sessions.length > 0) {
// Get the latest session (first in the list, assuming they're sorted by updatedAt)
const latestSession = sessions[0]
// Set the latest session as active
dispatch(setActiveSessionIdAction({ agentId, sessionId: latestSession.id }))
dispatch(setActiveTopicOrSessionAction('session'))
} else {
// No sessions exist, we might want to create one
// But for now, just switch to session view and let the Sessions component handle it
dispatch(setActiveTopicOrSessionAction('session'))
}
} catch (error) {
logger.error('Failed to initialize agent session:', error as Error)
// Even if loading fails, switch to session view
dispatch(setActiveTopicOrSessionAction('session'))
}
},
[client, dispatch, activeSessionId]
)
/**
* Auto-initialize when activeAgentId changes
*/
useEffect(() => {
if (activeAgentId && activeAgentId !== 'fake') {
// Check if we need to initialize this agent's session
const hasActiveSession = activeSessionId[activeAgentId]
if (!hasActiveSession) {
initializeAgentSession(activeAgentId)
}
}
}, [activeAgentId, activeSessionId, initializeAgentSession])
return {
initializeAgentSession
}
}

View File

@ -1,4 +1,5 @@
import { ErrorBoundary } from '@renderer/components/ErrorBoundary' import { ErrorBoundary } from '@renderer/components/ErrorBoundary'
import { useAgentSessionInitializer } from '@renderer/hooks/agents/useAgentSessionInitializer'
import { useAssistants } from '@renderer/hooks/useAssistant' import { useAssistants } from '@renderer/hooks/useAssistant'
import { useRuntime } from '@renderer/hooks/useRuntime' import { useRuntime } from '@renderer/hooks/useRuntime'
import { useNavbarPosition, useSettings } from '@renderer/hooks/useSettings' import { useNavbarPosition, useSettings } from '@renderer/hooks/useSettings'
@ -26,6 +27,9 @@ const HomePage: FC = () => {
const navigate = useNavigate() const navigate = useNavigate()
const { isLeftNavbar } = useNavbarPosition() const { isLeftNavbar } = useNavbarPosition()
// Initialize agent session hook
useAgentSessionInitializer()
const location = useLocation() const location = useLocation()
const state = location.state const state = location.state
@ -108,9 +112,9 @@ const HomePage: FC = () => {
createdAt: '', createdAt: '',
updatedAt: '', updatedAt: '',
messages: [] messages: []
} } as unknown as Topic
], ],
type: '' type: 'chat'
}) })
} else if (activeTopicOrSession === 'topic') { } else if (activeTopicOrSession === 'topic') {
dispatch(setActiveAgentId('fake')) dispatch(setActiveAgentId('fake'))

View File

@ -1,9 +1,10 @@
import { Alert, Button, Spinner } from '@heroui/react' import { Alert, Button, Spinner } from '@heroui/react'
import { AgentModal } from '@renderer/components/Popups/agent/AgentModal' import { AgentModal } from '@renderer/components/Popups/agent/AgentModal'
import { useAgents } from '@renderer/hooks/agents/useAgents' import { useAgents } from '@renderer/hooks/agents/useAgents'
import { useAgentSessionInitializer } from '@renderer/hooks/agents/useAgentSessionInitializer'
import { useRuntime } from '@renderer/hooks/useRuntime' import { useRuntime } from '@renderer/hooks/useRuntime'
import { useAppDispatch } from '@renderer/store' import { useAppDispatch } from '@renderer/store'
import { setActiveAgentId as setActiveAgentIdAction, setActiveTopicOrSessionAction } from '@renderer/store/runtime' import { setActiveAgentId as setActiveAgentIdAction } from '@renderer/store/runtime'
import { Plus } from 'lucide-react' import { Plus } from 'lucide-react'
import { FC, useCallback, useEffect } from 'react' import { FC, useCallback, useEffect } from 'react'
import { useTranslation } from 'react-i18next' import { useTranslation } from 'react-i18next'
@ -17,14 +18,17 @@ export const Agents: FC<AssistantsTabProps> = () => {
const { t } = useTranslation() const { t } = useTranslation()
const { chat } = useRuntime() const { chat } = useRuntime()
const { activeAgentId } = chat const { activeAgentId } = chat
const { initializeAgentSession } = useAgentSessionInitializer()
const dispatch = useAppDispatch() const dispatch = useAppDispatch()
const setActiveAgentId = useCallback( const setActiveAgentId = useCallback(
(id: string) => { async (id: string) => {
dispatch(setActiveAgentIdAction(id)) dispatch(setActiveAgentIdAction(id))
// Initialize the session for this agent
await initializeAgentSession(id)
}, },
[dispatch] [dispatch, initializeAgentSession]
) )
useEffect(() => { useEffect(() => {
@ -47,7 +51,6 @@ export const Agents: FC<AssistantsTabProps> = () => {
onDelete={() => deleteAgent(agent.id)} onDelete={() => deleteAgent(agent.id)}
onPress={() => { onPress={() => {
setActiveAgentId(agent.id) setActiveAgentId(agent.id)
dispatch(setActiveTopicOrSessionAction('session'))
}} }}
/> />
))} ))}