|
|
@@ -0,0 +1,434 @@
|
|
|
+// src/hooks/useAgentChat.ts
|
|
|
+'use client';
|
|
|
+
|
|
|
+import { useState, useEffect, useRef, useCallback } from 'react';
|
|
|
+import {
|
|
|
+ AgentMessage,
|
|
|
+ AgentSession,
|
|
|
+ AgentToolMetadata,
|
|
|
+ ToolStep,
|
|
|
+ AgentDangerousAction,
|
|
|
+} from '@/types/agent';
|
|
|
+import { agentService } from '@/lib/services/agentService';
|
|
|
+import { toast } from 'react-hot-toast';
|
|
|
+
|
|
|
+const SESSIONS_STORAGE_KEY = 'agent_sessions_list_v1';
|
|
|
+const ACTIVE_SESSION_STORAGE_KEY = 'agent_active_session_id';
|
|
|
+const MESSAGES_PREFIX = 'agent_messages_';
|
|
|
+
|
|
|
+const generateSessionId = () => {
|
|
|
+ return `sess_admin_${Date.now()}_${Math.random().toString(36).substring(2, 8)}`;
|
|
|
+};
|
|
|
+
|
|
|
+export function useAgentChat() {
|
|
|
+ const [sessions, setSessions] = useState<AgentSession[]>([]);
|
|
|
+ const [currentSessionId, setCurrentSessionId] = useState<string>('');
|
|
|
+ const [messages, setMessages] = useState<AgentMessage[]>([]);
|
|
|
+ const [isLoading, setIsLoading] = useState<boolean>(false);
|
|
|
+ const [currentThinking, setCurrentThinking] = useState<{ status: string; step?: number } | null>(null);
|
|
|
+ const [tools, setTools] = useState<AgentToolMetadata[]>([]);
|
|
|
+ const [toolsLoading, setToolsLoading] = useState<boolean>(false);
|
|
|
+
|
|
|
+ const abortControllerRef = useRef<AbortController | null>(null);
|
|
|
+
|
|
|
+ // 加载系统可用工具列表
|
|
|
+ const loadTools = useCallback(async () => {
|
|
|
+ setToolsLoading(true);
|
|
|
+ try {
|
|
|
+ const data = await agentService.getTools();
|
|
|
+ setTools(data);
|
|
|
+ } catch (err) {
|
|
|
+ console.error('加载 Agent 工具失败:', err);
|
|
|
+ } finally {
|
|
|
+ setToolsLoading(false);
|
|
|
+ }
|
|
|
+ }, []);
|
|
|
+
|
|
|
+ // 1. 初始化会话列表与当前会话
|
|
|
+ useEffect(() => {
|
|
|
+ loadTools();
|
|
|
+
|
|
|
+ try {
|
|
|
+ const savedSessionsStr = localStorage.getItem(SESSIONS_STORAGE_KEY);
|
|
|
+ const savedActiveId = localStorage.getItem(ACTIVE_SESSION_STORAGE_KEY);
|
|
|
+
|
|
|
+ let loadedSessions: AgentSession[] = [];
|
|
|
+ if (savedSessionsStr) {
|
|
|
+ loadedSessions = JSON.parse(savedSessionsStr);
|
|
|
+ }
|
|
|
+
|
|
|
+ if (loadedSessions.length === 0) {
|
|
|
+ const newId = generateSessionId();
|
|
|
+ const initialSession: AgentSession = {
|
|
|
+ id: newId,
|
|
|
+ title: '新建运维对话',
|
|
|
+ createdAt: Date.now(),
|
|
|
+ updatedAt: Date.now(),
|
|
|
+ messageCount: 0,
|
|
|
+ };
|
|
|
+ loadedSessions = [initialSession];
|
|
|
+ localStorage.setItem(SESSIONS_STORAGE_KEY, JSON.stringify(loadedSessions));
|
|
|
+ localStorage.setItem(ACTIVE_SESSION_STORAGE_KEY, newId);
|
|
|
+ setSessions(loadedSessions);
|
|
|
+ setCurrentSessionId(newId);
|
|
|
+ } else {
|
|
|
+ setSessions(loadedSessions);
|
|
|
+ const activeId = savedActiveId && loadedSessions.some((s) => s.id === savedActiveId)
|
|
|
+ ? savedActiveId
|
|
|
+ : loadedSessions[0].id;
|
|
|
+ setCurrentSessionId(activeId);
|
|
|
+ localStorage.setItem(ACTIVE_SESSION_STORAGE_KEY, activeId);
|
|
|
+ }
|
|
|
+ } catch (err) {
|
|
|
+ console.error('初始化会话失败:', err);
|
|
|
+ }
|
|
|
+ }, [loadTools]);
|
|
|
+
|
|
|
+ // 2. 当切换 currentSessionId 时加载消息
|
|
|
+ useEffect(() => {
|
|
|
+ if (!currentSessionId) return;
|
|
|
+ try {
|
|
|
+ const savedMessagesStr = localStorage.getItem(`${MESSAGES_PREFIX}${currentSessionId}`);
|
|
|
+ if (savedMessagesStr) {
|
|
|
+ setMessages(JSON.parse(savedMessagesStr));
|
|
|
+ } else {
|
|
|
+ setMessages([]);
|
|
|
+ }
|
|
|
+ } catch (err) {
|
|
|
+ console.error('读取会话消息失败:', err);
|
|
|
+ setMessages([]);
|
|
|
+ }
|
|
|
+ }, [currentSessionId]);
|
|
|
+
|
|
|
+ // 3. 持久化当前会话消息
|
|
|
+ const saveMessages = useCallback(
|
|
|
+ (sessionId: string, newMessages: AgentMessage[]) => {
|
|
|
+ setMessages(newMessages);
|
|
|
+ try {
|
|
|
+ localStorage.setItem(`${MESSAGES_PREFIX}${sessionId}`, JSON.stringify(newMessages));
|
|
|
+
|
|
|
+ // 同时更新 sessions 列表中的元数据 (最后一条消息摘要与更新时间)
|
|
|
+ setSessions((prevSessions) => {
|
|
|
+ const lastMsg = newMessages[newMessages.length - 1];
|
|
|
+ const snippet = lastMsg ? lastMsg.content.slice(0, 36) : '';
|
|
|
+ const updated = prevSessions.map((s) => {
|
|
|
+ if (s.id === sessionId) {
|
|
|
+ return {
|
|
|
+ ...s,
|
|
|
+ updatedAt: Date.now(),
|
|
|
+ messageCount: newMessages.length,
|
|
|
+ lastMessageSnippet: snippet,
|
|
|
+ title: s.title === '新建运维对话' && lastMsg?.role === 'user'
|
|
|
+ ? lastMsg.content.slice(0, 16) || '运维指令会话'
|
|
|
+ : s.title,
|
|
|
+ };
|
|
|
+ }
|
|
|
+ return s;
|
|
|
+ });
|
|
|
+ localStorage.setItem(SESSIONS_STORAGE_KEY, JSON.stringify(updated));
|
|
|
+ return updated;
|
|
|
+ });
|
|
|
+ } catch (err) {
|
|
|
+ console.error('保存会话消息失败:', err);
|
|
|
+ }
|
|
|
+ },
|
|
|
+ []
|
|
|
+ );
|
|
|
+
|
|
|
+ // 新建会话
|
|
|
+ const createNewSession = useCallback(() => {
|
|
|
+ if (abortControllerRef.current) {
|
|
|
+ abortControllerRef.current.abort();
|
|
|
+ }
|
|
|
+ const newId = generateSessionId();
|
|
|
+ const newSession: AgentSession = {
|
|
|
+ id: newId,
|
|
|
+ title: '新建运维对话',
|
|
|
+ createdAt: Date.now(),
|
|
|
+ updatedAt: Date.now(),
|
|
|
+ messageCount: 0,
|
|
|
+ };
|
|
|
+ const updated = [newSession, ...sessions];
|
|
|
+ setSessions(updated);
|
|
|
+ setCurrentSessionId(newId);
|
|
|
+ setMessages([]);
|
|
|
+ localStorage.setItem(SESSIONS_STORAGE_KEY, JSON.stringify(updated));
|
|
|
+ localStorage.setItem(ACTIVE_SESSION_STORAGE_KEY, newId);
|
|
|
+ toast.success('已开启新运维对话');
|
|
|
+ return newId;
|
|
|
+ }, [sessions]);
|
|
|
+
|
|
|
+ // 切换会话
|
|
|
+ const switchSession = useCallback((sessionId: string) => {
|
|
|
+ if (abortControllerRef.current) {
|
|
|
+ abortControllerRef.current.abort();
|
|
|
+ }
|
|
|
+ setCurrentSessionId(sessionId);
|
|
|
+ localStorage.setItem(ACTIVE_SESSION_STORAGE_KEY, sessionId);
|
|
|
+ }, []);
|
|
|
+
|
|
|
+ // 删除会话
|
|
|
+ const deleteSession = useCallback(
|
|
|
+ async (sessionId: string) => {
|
|
|
+ // 远程清除 Redis 记忆
|
|
|
+ agentService.deleteSession(sessionId).catch(() => {});
|
|
|
+
|
|
|
+ localStorage.removeItem(`${MESSAGES_PREFIX}${sessionId}`);
|
|
|
+ const remaining = sessions.filter((s) => s.id !== sessionId);
|
|
|
+
|
|
|
+ if (remaining.length === 0) {
|
|
|
+ const newId = generateSessionId();
|
|
|
+ const initialSession: AgentSession = {
|
|
|
+ id: newId,
|
|
|
+ title: '新建运维对话',
|
|
|
+ createdAt: Date.now(),
|
|
|
+ updatedAt: Date.now(),
|
|
|
+ messageCount: 0,
|
|
|
+ };
|
|
|
+ const resetSessions = [initialSession];
|
|
|
+ setSessions(resetSessions);
|
|
|
+ setCurrentSessionId(newId);
|
|
|
+ setMessages([]);
|
|
|
+ localStorage.setItem(SESSIONS_STORAGE_KEY, JSON.stringify(resetSessions));
|
|
|
+ localStorage.setItem(ACTIVE_SESSION_STORAGE_KEY, newId);
|
|
|
+ } else {
|
|
|
+ setSessions(remaining);
|
|
|
+ localStorage.setItem(SESSIONS_STORAGE_KEY, JSON.stringify(remaining));
|
|
|
+ if (currentSessionId === sessionId) {
|
|
|
+ setCurrentSessionId(remaining[0].id);
|
|
|
+ localStorage.setItem(ACTIVE_SESSION_STORAGE_KEY, remaining[0].id);
|
|
|
+ }
|
|
|
+ }
|
|
|
+ toast.success('会话已清除');
|
|
|
+ },
|
|
|
+ [sessions, currentSessionId]
|
|
|
+ );
|
|
|
+
|
|
|
+ // 清空当前会话消息与记忆
|
|
|
+ const clearCurrentSession = useCallback(async () => {
|
|
|
+ if (!currentSessionId) return;
|
|
|
+ if (abortControllerRef.current) {
|
|
|
+ abortControllerRef.current.abort();
|
|
|
+ }
|
|
|
+ await agentService.deleteSession(currentSessionId).catch(() => {});
|
|
|
+ localStorage.removeItem(`${MESSAGES_PREFIX}${currentSessionId}`);
|
|
|
+ setMessages([]);
|
|
|
+ setCurrentThinking(null);
|
|
|
+ setIsLoading(false);
|
|
|
+ toast.success('会话历史与上下文已重置');
|
|
|
+ }, [currentSessionId]);
|
|
|
+
|
|
|
+ // 中断当前流式生成
|
|
|
+ const abortStream = useCallback(() => {
|
|
|
+ if (abortControllerRef.current) {
|
|
|
+ abortControllerRef.current.abort();
|
|
|
+ abortControllerRef.current = null;
|
|
|
+ setIsLoading(false);
|
|
|
+ setCurrentThinking(null);
|
|
|
+ toast('已终止 Agent 执行');
|
|
|
+ }
|
|
|
+ }, []);
|
|
|
+
|
|
|
+ // 发送指令/需求
|
|
|
+ const sendMessage = useCallback(
|
|
|
+ async (text: string, contextHint?: string) => {
|
|
|
+ if (!text.trim() || isLoading) return;
|
|
|
+
|
|
|
+ const userMsgId = `msg_user_${Date.now()}`;
|
|
|
+ const assistantMsgId = `msg_ai_${Date.now()}`;
|
|
|
+
|
|
|
+ // 若有上下文(如当前处于某个管理路由),自动附加提示
|
|
|
+ const effectiveMessage = contextHint
|
|
|
+ ? `[系统上下文: ${contextHint}]\n${text}`
|
|
|
+ : text;
|
|
|
+
|
|
|
+ const userMessage: AgentMessage = {
|
|
|
+ id: userMsgId,
|
|
|
+ role: 'user',
|
|
|
+ content: text,
|
|
|
+ timestamp: Date.now(),
|
|
|
+ };
|
|
|
+
|
|
|
+ const initialAssistantMessage: AgentMessage = {
|
|
|
+ id: assistantMsgId,
|
|
|
+ role: 'assistant',
|
|
|
+ content: '',
|
|
|
+ timestamp: Date.now(),
|
|
|
+ isStreaming: true,
|
|
|
+ steps: [],
|
|
|
+ thinking: { status: 'started' },
|
|
|
+ };
|
|
|
+
|
|
|
+ const updatedHistory = [...messages, userMessage, initialAssistantMessage];
|
|
|
+ setMessages(updatedHistory);
|
|
|
+ setIsLoading(true);
|
|
|
+ setCurrentThinking({ status: 'started' });
|
|
|
+
|
|
|
+ abortControllerRef.current = new AbortController();
|
|
|
+
|
|
|
+ let currentAssistantContent = '';
|
|
|
+ const currentSteps: ToolStep[] = [];
|
|
|
+
|
|
|
+ try {
|
|
|
+ await agentService.chatStream(
|
|
|
+ {
|
|
|
+ message: effectiveMessage,
|
|
|
+ session_id: currentSessionId,
|
|
|
+ stream: true,
|
|
|
+ },
|
|
|
+ {
|
|
|
+ onThink: (step, status) => {
|
|
|
+ setCurrentThinking({ status: status || 'planning', step });
|
|
|
+ setMessages((prev) =>
|
|
|
+ prev.map((msg) =>
|
|
|
+ msg.id === assistantMsgId
|
|
|
+ ? { ...msg, thinking: { status: (status as any) || 'planning', step } }
|
|
|
+ : msg
|
|
|
+ )
|
|
|
+ );
|
|
|
+ },
|
|
|
+ onToolStart: (tool, args, callId) => {
|
|
|
+ const newStep: ToolStep = {
|
|
|
+ tool,
|
|
|
+ arguments: args,
|
|
|
+ call_id: callId,
|
|
|
+ status: 'running',
|
|
|
+ startedAt: Date.now(),
|
|
|
+ };
|
|
|
+ currentSteps.push(newStep);
|
|
|
+
|
|
|
+ // 检查工具是否属于危险/写操作
|
|
|
+ const matchedTool = tools.find((t) => t.name === tool);
|
|
|
+ let dangerousAction: AgentDangerousAction | undefined = undefined;
|
|
|
+ if (matchedTool?.is_dangerous || tool.includes('cancel') || tool.includes('delete')) {
|
|
|
+ dangerousAction = {
|
|
|
+ tool,
|
|
|
+ arguments: args,
|
|
|
+ call_id: callId,
|
|
|
+ description: matchedTool?.description || '执行写操作',
|
|
|
+ };
|
|
|
+ }
|
|
|
+
|
|
|
+ setMessages((prev) =>
|
|
|
+ prev.map((msg) =>
|
|
|
+ msg.id === assistantMsgId
|
|
|
+ ? {
|
|
|
+ ...msg,
|
|
|
+ steps: [...currentSteps],
|
|
|
+ dangerousAction: dangerousAction || msg.dangerousAction,
|
|
|
+ }
|
|
|
+ : msg
|
|
|
+ )
|
|
|
+ );
|
|
|
+ },
|
|
|
+ onToolEnd: (tool, result, isError, callId) => {
|
|
|
+ const target = currentSteps.find(
|
|
|
+ (s) => (callId && s.call_id === callId) || (!callId && s.tool === tool)
|
|
|
+ );
|
|
|
+ if (target) {
|
|
|
+ target.result = result;
|
|
|
+ target.is_error = isError;
|
|
|
+ target.status = isError ? 'failed' : 'completed';
|
|
|
+ target.completedAt = Date.now();
|
|
|
+ }
|
|
|
+ setMessages((prev) =>
|
|
|
+ prev.map((msg) =>
|
|
|
+ msg.id === assistantMsgId
|
|
|
+ ? {
|
|
|
+ ...msg,
|
|
|
+ steps: [...currentSteps],
|
|
|
+ }
|
|
|
+ : msg
|
|
|
+ )
|
|
|
+ );
|
|
|
+ },
|
|
|
+ onMessage: (delta, full) => {
|
|
|
+ currentAssistantContent = full || currentAssistantContent + delta;
|
|
|
+ setMessages((prev) =>
|
|
|
+ prev.map((msg) =>
|
|
|
+ msg.id === assistantMsgId
|
|
|
+ ? {
|
|
|
+ ...msg,
|
|
|
+ content: currentAssistantContent,
|
|
|
+ }
|
|
|
+ : msg
|
|
|
+ )
|
|
|
+ );
|
|
|
+ },
|
|
|
+ onFinish: (finalAnswer, stepsCount, resSessionId) => {
|
|
|
+ const finalContent = finalAnswer || currentAssistantContent;
|
|
|
+ const finalMessage: AgentMessage = {
|
|
|
+ id: assistantMsgId,
|
|
|
+ role: 'assistant',
|
|
|
+ content: finalContent,
|
|
|
+ timestamp: Date.now(),
|
|
|
+ isStreaming: false,
|
|
|
+ steps: [...currentSteps],
|
|
|
+ thinking: undefined,
|
|
|
+ };
|
|
|
+
|
|
|
+ const finalMessages = [
|
|
|
+ ...updatedHistory.slice(0, -1),
|
|
|
+ finalMessage,
|
|
|
+ ];
|
|
|
+ saveMessages(currentSessionId, finalMessages);
|
|
|
+ setIsLoading(false);
|
|
|
+ setCurrentThinking(null);
|
|
|
+ },
|
|
|
+ onError: (err: any) => {
|
|
|
+ const errMsg = typeof err === 'string' ? err : err?.message || '请求发生未知错误';
|
|
|
+ setMessages((prev) =>
|
|
|
+ prev.map((msg) =>
|
|
|
+ msg.id === assistantMsgId
|
|
|
+ ? {
|
|
|
+ ...msg,
|
|
|
+ isStreaming: false,
|
|
|
+ error: errMsg,
|
|
|
+ content: msg.content || `⚠️ [Agent 异常] ${errMsg}`,
|
|
|
+ }
|
|
|
+ : msg
|
|
|
+ )
|
|
|
+ );
|
|
|
+ setIsLoading(false);
|
|
|
+ setCurrentThinking(null);
|
|
|
+ toast.error(`Agent 异常: ${errMsg}`);
|
|
|
+ },
|
|
|
+ },
|
|
|
+ abortControllerRef.current.signal
|
|
|
+ );
|
|
|
+ } catch (err: any) {
|
|
|
+ console.error('Agent chat error:', err);
|
|
|
+ setIsLoading(false);
|
|
|
+ setCurrentThinking(null);
|
|
|
+ }
|
|
|
+ },
|
|
|
+ [currentSessionId, isLoading, messages, tools, saveMessages]
|
|
|
+ );
|
|
|
+
|
|
|
+ // 确认并下发高危操作二次确认
|
|
|
+ const handleConfirmDangerousAction = useCallback(
|
|
|
+ (action: AgentDangerousAction) => {
|
|
|
+ const confirmPrompt = `确认执行操作:【${action.tool}】,参数为:${JSON.stringify(action.arguments)}。请继续处理。`;
|
|
|
+ sendMessage(confirmPrompt);
|
|
|
+ },
|
|
|
+ [sendMessage]
|
|
|
+ );
|
|
|
+
|
|
|
+ return {
|
|
|
+ sessions,
|
|
|
+ currentSessionId,
|
|
|
+ messages,
|
|
|
+ isLoading,
|
|
|
+ currentThinking,
|
|
|
+ tools,
|
|
|
+ toolsLoading,
|
|
|
+ sendMessage,
|
|
|
+ abortStream,
|
|
|
+ createNewSession,
|
|
|
+ switchSession,
|
|
|
+ deleteSession,
|
|
|
+ clearCurrentSession,
|
|
|
+ handleConfirmDangerousAction,
|
|
|
+ loadTools,
|
|
|
+ };
|
|
|
+}
|