From c7d050f1bc2541a0cc27fb7f866ab1152843529e Mon Sep 17 00:00:00 2001 From: attacker Date: Fri, 10 Jul 2026 01:23:34 +0800 Subject: [PATCH] =?UTF-8?q?Q34:=20AIOpsAssistant=20=E5=B7=A8=E5=9E=8B?= =?UTF-8?q?=E7=BB=84=E4=BB=B6=E6=8B=86=E5=88=86=20(505L=E2=86=92288L,=20?= =?UTF-8?q?=E6=8F=90=E5=8F=96=20aiops-assistant/=205=20=E6=96=87=E4=BB=B6)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit AIOpsAssistant.tsx (505L) → 288L (-43%) 提取 5 个独立文件到 aiops-assistant/ 子目录: - types.ts (39L): Message/QuickAction 接口 + defaultConfig + fmtTime - context-loaders.ts (69L): loadAlertsContext/loadMetricsContext/loadReportContext 3 个平台数据加载纯函数 (告警/Agent指标/仪表盘综合数据) - quick-actions.tsx (17L): quickActions 数组 (4 快捷操作) - ChatMessage.tsx (47L): 消息气泡 (streaming/thinking/error 三态 + 光标) - AssistantSidebar.tsx (76L): 快捷操作卡片 + 能力清单卡片 验证: tsc -b=0, npm build✓ (17.68s), ESLint errors=0/any=0, go build=0, 17/17 集成测试通过 --- ROADMAP.md | 1 + .../src/components/aiops/AIOpsAssistant.tsx | 393 ++++-------------- .../aiops-assistant/AssistantSidebar.tsx | 76 ++++ .../aiops/aiops-assistant/ChatMessage.tsx | 47 +++ .../aiops/aiops-assistant/context-loaders.ts | 69 +++ .../aiops/aiops-assistant/quick-actions.tsx | 17 + .../components/aiops/aiops-assistant/types.ts | 39 ++ 7 files changed, 337 insertions(+), 305 deletions(-) create mode 100644 frontend/src/components/aiops/aiops-assistant/AssistantSidebar.tsx create mode 100644 frontend/src/components/aiops/aiops-assistant/ChatMessage.tsx create mode 100644 frontend/src/components/aiops/aiops-assistant/context-loaders.ts create mode 100644 frontend/src/components/aiops/aiops-assistant/quick-actions.tsx create mode 100644 frontend/src/components/aiops/aiops-assistant/types.ts diff --git a/ROADMAP.md b/ROADMAP.md index 49366d8..88359a3 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -505,6 +505,7 @@ services/api.ts (1324L) | Q31 | 前端巨型组件拆分(PromDsFormDialog 528L→294L (-44%),提取 6 个文件 (CollapsibleSection 42L 通用折叠包装器 DRY 3 个重复折叠模式 + AuthSection 107L 认证折叠 + HeadersSection 64L 自定义Headers + AlertingSection 58L 告警折叠 + MiscSection 47L 杂项折叠 + TestResultBanner 32L 测试结果横幅),3 个折叠区块全部使用共享 CollapsibleSection 消除重复 JSX)) | P0 | **done** | | Q32 | 前端巨型组件拆分(AuditOperationsTab 527L→275L (-48%),提取 audit-operations/ 3 个文件 (types 43L normalizeLog 纯函数+AuditStatistics 接口 + LogDetailDialog 85L 详情弹窗+DetailRow + StatisticsDialog 108L 统计弹窗+StatCard),清除死代码 useConfirm/_confirm/_handleShowStats/statsOpen/statistics/statsLoading,ESLint errors=0/any=0,tsc -b=0,npm build✓,go build=0,17/17 测试通过) | P0 | **done** | | Q33 | 前端巨型组件拆分(DashboardRecent 518L→25L (-95%),提取 dashboard-recent/ 7 个文件 (types 48L + shared-components(StatusDot/SeverityBadge) 35L + AlertMessagesCard 72L + CertificateExpiryCard 99L + ReleaseHistoryCard 99L + OpsOverviewCard 77L + KubernetesClusterCard 97L),主文件改为 barrel re-export 保持向后兼容,tsc -b=0,npm build✓,ESLint=0/0/0,go build=0,17/17 测试通过) | P0 | **done** | +| Q34 | 前端巨型组件拆分(AIOpsAssistant 505L→288L (-43%),提取 aiops-assistant/ 5 个文件 (types 39L Message/QuickAction/defaultConfig/fmtTime + context-loaders.ts 69L loadAlerts/loadMetrics/loadReport 3 个平台数据加载纯函数 + quick-actions.tsx 17L + ChatMessage 47L 消息气泡(含 streaming/thinking/error 状态) + AssistantSidebar 76L 快捷操作+能力卡片),tsc -b=0,npm build✓,ESLint=0/0/0,go build=0,17/17 测试通过) | P0 | **done** | --- diff --git a/frontend/src/components/aiops/AIOpsAssistant.tsx b/frontend/src/components/aiops/AIOpsAssistant.tsx index 15f1ed4..94c336a 100644 --- a/frontend/src/components/aiops/AIOpsAssistant.tsx +++ b/frontend/src/components/aiops/AIOpsAssistant.tsx @@ -1,144 +1,31 @@ import { useState, useRef, useEffect } from 'react'; import { useNavigate } from 'react-router-dom'; -import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'; +import { Card, CardContent, CardHeader } from '@/components/ui/card'; import { Button } from '@/components/ui/button'; import { Input } from '@/components/ui/input'; import { Badge } from '@/components/ui/badge'; import { ScrollArea } from '@/components/ui/scroll-area'; -import { Avatar, AvatarFallback } from '@/components/ui/avatar'; import { toast } from 'sonner'; -import { aiApi, alertApi, agentApi, dashboardStatsApi, type LLMConfigData, type ChatHistoryItem } from '@/api'; +import { aiApi, type LLMConfigData, type ChatHistoryItem } from '@/api'; import { Bot, Send, Settings, - AlertTriangle, - Activity, - FileText, - TrendingUp, - Terminal, RotateCw, - User, MessageSquare, Brain, - Loader2, CheckCircle2, Square, } from 'lucide-react'; import type { JsonData } from '@/types/common'; import { PageShell } from '@/components/layout/PageShell'; import { useTranslation } from 'react-i18next'; -import i18n from '@/i18n'; -const defaultConfig: LLMConfigData = { - provider: 'openai', - model: 'gpt-4o-mini', - api_key: '', - endpoint: 'https://api.openai.com/v1', - temperature: 0.7, - max_tokens: 2000, - system_prompt: '', - enabled: false, - reasoning_enabled: false, -}; - -// ============ 快捷操作平台数据加载器(注入真实运维上下文) // Logan.Li ============ -// 拉取最近告警事件,格式化为紧凑列表供 LLM 分析 -async function loadAlertsContext(): Promise { - const res = await alertApi.getAlerts({ page: 1, page_size: 20 }); - const alerts: JsonData[] = (res as JsonData)?.list || []; - if (!alerts.length) return i18n.t('aiops.noAlertsNow'); - const lines = alerts.slice(0, 15).map((a, i) => - `${i + 1}. [${a.severity || i18n.t('common.unknown')}|${a.status || '-'}] ${a.rule_name || i18n.t('dashboard.stat.alerts')} → 目标:${a.target || '-'} 值:${a.value ?? '-'} 时间:${(a.started_at || '').slice(0, 16)}`, - ); - const firing = alerts.filter((a) => a.status === 'firing').length; - return `共 ${alerts.length} 条告警(firing ${firing} 条),前 ${Math.min(15, alerts.length)} 条:\n${lines.join('\n')}`; -} - -// 拉取 Agent 实时主机指标,识别高负载主机 -async function loadMetricsContext(): Promise { - const res = await agentApi.getLatest(); - const hosts: JsonData[] = Array.isArray(res) ? res : (res as JsonData)?.list || []; - if (!hosts.length) return i18n.t('aiops.noAgentData'); - const lines = hosts.slice(0, 20).map((h, i) => { - const cpu = h.cpu_usage ?? '-'; - const mem = h.mem_usage ?? '-'; - return `${i + 1}. ${h.hostname || '-'} | CPU:${cpu}% | 内存:${mem}% (${h.mem_used ?? '-'}/${h.mem_total ?? '-'}GB) | 核数:${h.cpu_cores ?? '-'} | 上报:${(h.report_time || '').slice(0, 16)}`; - }); - const hot = hosts.filter((h) => (h.cpu_usage ?? 0) >= 80 || (h.mem_usage ?? 0) >= 80); - const note = hot.length - ? `\n⚠️ 高负载主机 ${hot.length} 台:${hot.map((h) => `${h.hostname}(CPU${h.cpu_usage}%/MEM${h.mem_usage}%)`).join('、')}` - : ''; - return `Agent 监控的 ${hosts.length} 台主机实时指标:\n${lines.join('\n')}${note}`; -} - -// 拉取仪表盘综合数据,生成运维报告上下文 -async function loadReportContext(): Promise { - const summary = await aiApi.getContextSummary(); - if (summary) { - const alertLines = (summary.recent_alerts || []).slice(0, 10).map((a, i) => - `${i + 1}.[${a.severity || '?'}|${a.status || '?'}] ${a.rule_name || '-'} → ${a.target || '-'}`, - ); - const highLoadLines = (summary.high_load_hosts || []).slice(0, 8).map((h, i) => - `${i + 1}.${h.hostname || h.ip} CPU:${h.cpu_usage}% MEM:${h.memory_usage}% DISK:${h.disk_usage}% Agent:${h.agent_status}`, - ); - return [ - `平台概览:服务器:${summary.server_total}(在线${summary.server_online}) | Kubernetes集群:${summary.cluster_total} | 平台告警:${summary.firing_alerts} | Agent未恢复告警:${summary.unresolved_alerts}`, - '', - '高负载资产:', - highLoadLines.join('\n') || i18n.t('aiops.noneFallback'), - '', - '最近告警:', - alertLines.join('\n') || i18n.t('aiops.noneFallback'), - ].join('\n'); - } - - const [stats, alerts, releases] = await Promise.all([ - dashboardStatsApi.getStats().catch(() => null), - dashboardStatsApi.getAlerts(10).catch(() => null), - dashboardStatsApi.getReleases(10).catch(() => null), - ]); - const s: JsonData = stats || {}; - const ss = s.server_stats || {}, ks = s.kubernetes_stats || {}, as = s.alert_stats || {}, ps = s.pipeline_stats || {}, cs = s.cost_stats || {}; - const overview = `服务器:${ss.total ?? 0}(运行${ss.running ?? 0}) | Kubernetes集群:${ks.total ?? 0} 节点:${ks.total_nodes ?? 0} Pod:${ks.total_pods ?? 0} | 告警:${as.total ?? 0}(firing ${as.firing ?? 0}) | 流水线:${ps.total ?? 0}(成功率${ps.success_rate ?? 0}%) | 本月成本:¥${cs.month_cost ?? 0}`; - const alertList: JsonData[] = Array.isArray(alerts) ? alerts : (alerts as JsonData)?.list || []; - const releaseList: JsonData[] = Array.isArray(releases) ? releases : (releases as JsonData)?.list || []; - const alertLines = alertList.slice(0, 10).map((a, i) => `${i + 1}.[${a.severity || '?'}|${a.status || '?'}] ${a.rule_name || '-'} → ${a.target || '-'}`); - const releaseLines = releaseList.slice(0, 10).map((r, i) => `${i + 1}.${r.app_name || '-'} ${r.version || ''} [${r.environment || '-'}/${r.status || '-'}] by ${r.author || '-'}`); - return `平台概览:${overview}\n\n最近告警:\n${alertLines.join('\n') || i18n.t('aiops.noneFallback')}\n\n最近发布:\n${releaseLines.join('\n') || i18n.t('aiops.noneFallback')}`; -} - -// 快捷操作类型(contextLoader 可选,支持未来无数据加载的纯文本操作) // Logan.Li -interface QuickAction { - id: string; - name: string; - icon: typeof AlertTriangle; - prompt: string; - contextLoader?: () => Promise; -} - -// 快捷操作(已配置 LLM 时自动拉取真实平台数据注入上下文后发送) // Logan.Li -const quickActions: QuickAction[] = [ - { id: 'alerts', name: i18n.t('aiops.analyzeTodayAlerts'), icon: AlertTriangle, prompt: i18n.t('aiops.analyzeAlertsPrompt'), contextLoader: loadAlertsContext }, - { id: 'performance', name: i18n.t('aiops.perfAnalysis'), icon: Activity, prompt: i18n.t('aiops.perfBottleneckPrompt'), contextLoader: loadMetricsContext }, - { id: 'report', name: i18n.t('aiops.dailyOpsReport'), icon: FileText, prompt: i18n.t('aiops.opsReportPrompt'), contextLoader: loadReportContext }, - { id: 'optimize', name: i18n.t('aiops.resourceOptAdvice'), icon: TrendingUp, prompt: i18n.t('aiops.capacityPlanPrompt'), contextLoader: loadMetricsContext }, -]; - -interface Message { - id: string; - role: 'user' | 'assistant'; - content: string; - timestamp: string; - isError?: boolean; - isStopped?: boolean; -} - -// 格式化时间为 HH:MM // Logan.Li -function fmtTime(iso: string): string { - const d = new Date(iso); - return d.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' }); -} +import type { Message, QuickAction } from './aiops-assistant/types'; +import { defaultConfig } from './aiops-assistant/types'; +import { quickActions } from './aiops-assistant/quick-actions'; +import { ChatMessage } from './aiops-assistant/ChatMessage'; +import { AssistantSidebar } from './aiops-assistant/AssistantSidebar'; export function AIOpsAssistant() { const { t } = useTranslation(); @@ -146,15 +33,12 @@ export function AIOpsAssistant() { const [messages, setMessages] = useState([]); const [input, setInput] = useState(''); const [isLoading, setIsLoading] = useState(false); - // 用于中止流式生成(点击t('common.stop')按钮时 abort) // Logan.Li const abortRef = useRef(null); - // 组件卸载时中止进行中的流式请求,避免 setState on unmounted // Logan.Li useEffect(() => () => abortRef.current?.abort(), []); const [config, setConfig] = useState(defaultConfig); - const [configReady, setConfigReady] = useState(false); // 已配置且启用 - const [contextLoading, setContextLoading] = useState(null); // 快捷操作拉取平台数据中 - // 会话 ID:前端生成 UUID,用于隔离多轮对话 // Logan.Li - // crypto.randomUUID() 需要 HTTPS/secure context,HTTP 环境用 fallback + const [configReady, setConfigReady] = useState(false); + const [contextLoading, setContextLoading] = useState(null); + const generateUUID = (): string => { try { return crypto.randomUUID(); } catch { /* HTTP fallback below */ } return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => { @@ -165,11 +49,9 @@ export function AIOpsAssistant() { const [sessionId, setSessionId] = useState(() => generateUUID()); const messagesEndRef = useRef(null); - // 滚动到底部 // Logan.Li const scrollToBottom = () => messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' }); useEffect(() => { scrollToBottom(); }, [messages]); - // 加载 LLM 配置 // Logan.Li const loadConfig = async () => { try { const cfg = await aiApi.getConfig(); @@ -180,7 +62,6 @@ export function AIOpsAssistant() { } }; - // 加载历史对话(按 session 隔离) // Logan.Li const loadHistory = async () => { try { const res = await aiApi.getHistory(sessionId); @@ -203,7 +84,6 @@ export function AIOpsAssistant() { // eslint-disable-next-line react-hooks/exhaustive-deps }, []); - // 发送一条消息的核心逻辑(流式输出,逐步填充助手气泡) // Logan.Li const sendMessage = async (text: string) => { const userMsg: Message = { id: Date.now().toString(), @@ -215,24 +95,19 @@ export function AIOpsAssistant() { const newMessages: Message[] = [ ...messages, userMsg, - // 预先插入空助手消息,随流式内容逐步填充 { id: assistantId, role: 'assistant', content: '', timestamp: new Date().toISOString() }, ]; setMessages(newMessages); setIsLoading(true); - // 创建 AbortController 以支持\"停止生成\" // Logan.Li const controller = new AbortController(); abortRef.current = controller; - // 用于在收到第一个 chunk 前显示t('aiops.thinking')占位 let firstChunkArrived = false; try { - // 仅保留最近 10 条上下文避免 token 超限(不含刚插入的空助手消息) // Logan.Li const history = [...messages, userMsg] .slice(-10) .map((m) => ({ role: m.role, content: m.content })); await aiApi.chatStream(history, (delta) => { firstChunkArrived = true; - // 逐块追加到助手消息内容 setMessages((prev) => prev.map((m) => m.id === assistantId ? { ...m, content: m.content + delta } : m, @@ -240,7 +115,6 @@ export function AIOpsAssistant() { ); }, controller.signal, sessionId); } catch (e) { - // 用户主动中止:保留已生成的部分内容,不当作错误 // Logan.Li if (controller.signal.aborted) { setMessages((prev) => prev.map((m) => @@ -273,7 +147,6 @@ export function AIOpsAssistant() { } }; - // 输入框发送 // Logan.Li const handleSend = async () => { const text = input.trim(); if (!text || isLoading) return; @@ -281,15 +154,12 @@ export function AIOpsAssistant() { await sendMessage(text); }; - // 快捷操作:已配置 LLM 时拉取真实平台数据注入上下文后自动发送;未配置则仅填入输入框 // Logan.Li const handleQuickAction = async (action: QuickAction) => { if (isLoading || contextLoading) return; - // 未配置或无数据加载器时,回退到填入输入框 if (!configReady || !action.contextLoader) { setInput(action.prompt); return; } - // 拉取真实平台数据,失败时注入错误说明而非中断 setContextLoading(action.id); let context = ''; try { @@ -303,7 +173,6 @@ export function AIOpsAssistant() { await sendMessage(fullPrompt); }; - // 新对话(生成新 session_id,清空本地 + 后端持久化历史) // Logan.Li const handleNewChat = async () => { try { await aiApi.clearHistory(); @@ -317,7 +186,6 @@ export function AIOpsAssistant() { toast.success(t('aiops.newConversationStarted')); }; - return ( - {/* Sidebar */} -
- - - {t('aiops.quickActions')} - - - {quickActions.map((action) => ( - - ))} - - +
+ +
- - - {t('aiops.capabilities')} - - -
- - {t('aiops.alertAnalysisTitle')} -
-
- - {t('aiops.performanceBottleneck')} -
-
- - {t('aiops.autoReportGen')} -
-
- - {t('aiops.autoScriptGenerated')} -
-
-
-
+ + +
+
+ + {t('aiops.aiAssistantShort')} + {configReady ? ( + + + {t('common.online')} + + ) : ( + {t('common.offline')} + )} +
+ +
+
- {/* Chat Area */} - - -
-
- - {t('aiops.aiAssistantShort')} - {configReady ? ( - - - {t('common.online')} - - ) : ( - {t('common.offline')} + +
+ {messages.length === 0 && !isLoading && ( +
+ +

{configReady ? t('aiops.emptyConvHint') : t('aiops.aiNotConfigured')}

+ {!configReady && ( + )}
- -
- + )} + {messages.map((message) => ( + + ))} +
+
+
- -
- {messages.length === 0 && !isLoading && ( -
- -

{configReady ? t('aiops.emptyConvHint') : t('aiops.aiNotConfigured')}

- {!configReady && ( - - )} -
- )} - {messages.map((message) => { - // 流式中:助手消息内容为空且正在加载时显示t('aiops.thinking')占位 // Logan.Li - const isStreaming = isLoading && message.role === 'assistant' && message.content === ''; - return ( -
- - - {message.role === 'assistant' ? : } - - -
-
- {isStreaming ? ( -
- - {t('aiops.thinking')} -
- ) : ( - message.content - )} - {/* 流式接收中且已有内容时,显示末尾闪烁光标提示 */} - {isLoading && message.role === 'assistant' && !isStreaming && message.content && ( - - )} -
-
- {fmtTime(message.timestamp)} - {message.isStopped && {t('aiops.stoppedParen')}} -
-
-
- ); - })} - {/* 流式输出时占位气泡已包含t('aiops.thinking')提示,无需独立 spinner */} -
-
- - - -
- setInput(e.target.value)} - onKeyDown={(e) => e.key === 'Enter' && handleSend()} - placeholder={configReady ? t('aiops.assistantPlaceholder') : t('aiops.configLlmFirst')} - className="flex-1 dg-input" - disabled={isLoading} - /> - + {isLoading && ( + - {/* 流式生成中显示\"停止生成\"按钮,中止当前请求 // Logan.Li */} - {isLoading && ( - - )} -
-
- + )} +
+ + ); } diff --git a/frontend/src/components/aiops/aiops-assistant/AssistantSidebar.tsx b/frontend/src/components/aiops/aiops-assistant/AssistantSidebar.tsx new file mode 100644 index 0000000..dbceb78 --- /dev/null +++ b/frontend/src/components/aiops/aiops-assistant/AssistantSidebar.tsx @@ -0,0 +1,76 @@ +import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'; +import { Button } from '@/components/ui/button'; +import { Loader2, AlertTriangle, Activity, FileText, Terminal } from 'lucide-react'; +import { useTranslation } from 'react-i18next'; +import type { QuickAction } from './types'; + +export function AssistantSidebar({ + actions, + isLoading, + contextLoading, + configReady, + onAction, +}: { + actions: QuickAction[]; + isLoading: boolean; + contextLoading: string | null; + configReady: boolean; + onAction: (action: QuickAction) => void; +}) { + const { t } = useTranslation(); + + return ( +
+ + + {t('aiops.quickActions')} + + + {actions.map((action) => ( + + ))} + + + + + + {t('aiops.capabilities')} + + +
+ + {t('aiops.alertAnalysisTitle')} +
+
+ + {t('aiops.performanceBottleneck')} +
+
+ + {t('aiops.autoReportGen')} +
+
+ + {t('aiops.autoScriptGenerated')} +
+
+
+
+ ); +} diff --git a/frontend/src/components/aiops/aiops-assistant/ChatMessage.tsx b/frontend/src/components/aiops/aiops-assistant/ChatMessage.tsx new file mode 100644 index 0000000..5ea8284 --- /dev/null +++ b/frontend/src/components/aiops/aiops-assistant/ChatMessage.tsx @@ -0,0 +1,47 @@ +import { Avatar, AvatarFallback } from '@/components/ui/avatar'; +import { Bot, User, Loader2 } from 'lucide-react'; +import { useTranslation } from 'react-i18next'; +import type { Message } from './types'; +import { fmtTime } from './types'; + +export function ChatMessage({ message, isLoading }: { message: Message; isLoading: boolean }) { + const { t } = useTranslation(); + const isStreaming = isLoading && message.role === 'assistant' && message.content === ''; + + return ( +
+ + + {message.role === 'assistant' ? : } + + +
+
+ {isStreaming ? ( +
+ + {t('aiops.thinking')} +
+ ) : ( + message.content + )} + {isLoading && message.role === 'assistant' && !isStreaming && message.content && ( + + )} +
+
+ {fmtTime(message.timestamp)} + {message.isStopped && {t('aiops.stoppedParen')}} +
+
+
+ ); +} diff --git a/frontend/src/components/aiops/aiops-assistant/context-loaders.ts b/frontend/src/components/aiops/aiops-assistant/context-loaders.ts new file mode 100644 index 0000000..d5b49a3 --- /dev/null +++ b/frontend/src/components/aiops/aiops-assistant/context-loaders.ts @@ -0,0 +1,69 @@ +import { alertApi, agentApi, aiApi, dashboardStatsApi } from '@/api'; +import type { JsonData } from '@/types/common'; +import i18n from '@/i18n'; + +/** 拉取最近告警事件,格式化为紧凑列表供 LLM 分析 */ +export async function loadAlertsContext(): Promise { + const res = await alertApi.getAlerts({ page: 1, page_size: 20 }); + const alerts: JsonData[] = (res as JsonData)?.list || []; + if (!alerts.length) return i18n.t('aiops.noAlertsNow'); + const lines = alerts.slice(0, 15).map((a, i) => + `${i + 1}. [${a.severity || i18n.t('common.unknown')}|${a.status || '-'}] ${a.rule_name || i18n.t('dashboard.stat.alerts')} → 目标:${a.target || '-'} 值:${a.value ?? '-'} 时间:${(a.started_at || '').slice(0, 16)}`, + ); + const firing = alerts.filter((a) => a.status === 'firing').length; + return `共 ${alerts.length} 条告警(firing ${firing} 条),前 ${Math.min(15, alerts.length)} 条:\n${lines.join('\n')}`; +} + +/** 拉取 Agent 实时主机指标,识别高负载主机 */ +export async function loadMetricsContext(): Promise { + const res = await agentApi.getLatest(); + const hosts: JsonData[] = Array.isArray(res) ? res : (res as JsonData)?.list || []; + if (!hosts.length) return i18n.t('aiops.noAgentData'); + const lines = hosts.slice(0, 20).map((h, i) => { + const cpu = h.cpu_usage ?? '-'; + const mem = h.mem_usage ?? '-'; + return `${i + 1}. ${h.hostname || '-'} | CPU:${cpu}% | 内存:${mem}% (${h.mem_used ?? '-'}/${h.mem_total ?? '-'}GB) | 核数:${h.cpu_cores ?? '-'} | 上报:${(h.report_time || '').slice(0, 16)}`; + }); + const hot = hosts.filter((h) => (h.cpu_usage ?? 0) >= 80 || (h.mem_usage ?? 0) >= 80); + const note = hot.length + ? `\n⚠️ 高负载主机 ${hot.length} 台:${hot.map((h) => `${h.hostname}(CPU${h.cpu_usage}%/MEM${h.mem_usage}%)`).join('、')}` + : ''; + return `Agent 监控的 ${hosts.length} 台主机实时指标:\n${lines.join('\n')}${note}`; +} + +/** 拉取仪表盘综合数据,生成运维报告上下文 */ +export async function loadReportContext(): Promise { + const summary = await aiApi.getContextSummary(); + if (summary) { + const alertLines = (summary.recent_alerts || []).slice(0, 10).map((a: JsonData, i: number) => + `${i + 1}.[${a.severity || '?'}|${a.status || '?'}] ${a.rule_name || '-'} → ${a.target || '-'}`, + ); + const highLoadLines = (summary.high_load_hosts || []).slice(0, 8).map((h: JsonData, i: number) => + `${i + 1}.${h.hostname || h.ip} CPU:${h.cpu_usage}% MEM:${h.memory_usage}% DISK:${h.disk_usage}% Agent:${h.agent_status}`, + ); + return [ + `平台概览:服务器:${summary.server_total}(在线${summary.server_online}) | Kubernetes集群:${summary.cluster_total} | 平台告警:${summary.firing_alerts} | Agent未恢复告警:${summary.unresolved_alerts}`, + '', + '高负载资产:', + highLoadLines.join('\n') || i18n.t('aiops.noneFallback'), + '', + '最近告警:', + alertLines.join('\n') || i18n.t('aiops.noneFallback'), + ].join('\n'); + } + + const [stats, alerts, releases] = await Promise.all([ + dashboardStatsApi.getStats().catch(() => null), + dashboardStatsApi.getAlerts(10).catch(() => null), + dashboardStatsApi.getReleases(10).catch(() => null), + ]); + + const s: JsonData = stats || {}; + const ss = s.server_stats || {}, ks = s.kubernetes_stats || {}, as = s.alert_stats || {}, ps = s.pipeline_stats || {}, cs = s.cost_stats || {}; + const overview = `服务器:${ss.total ?? 0}(运行${ss.running ?? 0}) | Kubernetes集群:${ks.total ?? 0} 节点:${ks.total_nodes ?? 0} Pod:${ks.total_pods ?? 0} | 告警:${as.total ?? 0}(firing ${as.firing ?? 0}) | 流水线:${ps.total ?? 0}(成功率${ps.success_rate ?? 0}%) | 本月成本:¥${cs.month_cost ?? 0}`; + const alertList: JsonData[] = Array.isArray(alerts) ? alerts : (alerts as JsonData)?.list || []; + const releaseList: JsonData[] = Array.isArray(releases) ? releases : (releases as JsonData)?.list || []; + const alertLines = alertList.slice(0, 10).map((a: JsonData, i: number) => `${i + 1}.[${a.severity || '?'}|${a.status || '?'}] ${a.rule_name || '-'} → ${a.target || '-'}`); + const releaseLines = releaseList.slice(0, 10).map((r: JsonData, i: number) => `${i + 1}.${r.app_name || '-'} ${r.version || ''} [${r.environment || '-'}/${r.status || '-'}] by ${r.author || '-'}`); + return `平台概览:${overview}\n\n最近告警:\n${alertLines.join('\n') || i18n.t('aiops.noneFallback')}\n\n最近发布:\n${releaseLines.join('\n') || i18n.t('aiops.noneFallback')}`; +} diff --git a/frontend/src/components/aiops/aiops-assistant/quick-actions.tsx b/frontend/src/components/aiops/aiops-assistant/quick-actions.tsx new file mode 100644 index 0000000..1cbdc65 --- /dev/null +++ b/frontend/src/components/aiops/aiops-assistant/quick-actions.tsx @@ -0,0 +1,17 @@ +import { + AlertTriangle, + Activity, + FileText, + TrendingUp, +} from 'lucide-react'; +import i18n from '@/i18n'; +import type { QuickAction } from './types'; +import { loadAlertsContext, loadMetricsContext, loadReportContext } from './context-loaders'; + +/** 快捷操作(已配置 LLM 时自动拉取真实平台数据注入上下文后发送) */ +export const quickActions: QuickAction[] = [ + { id: 'alerts', name: i18n.t('aiops.analyzeTodayAlerts'), icon: AlertTriangle, prompt: i18n.t('aiops.analyzeAlertsPrompt'), contextLoader: loadAlertsContext }, + { id: 'performance', name: i18n.t('aiops.perfAnalysis'), icon: Activity, prompt: i18n.t('aiops.perfBottleneckPrompt'), contextLoader: loadMetricsContext }, + { id: 'report', name: i18n.t('aiops.dailyOpsReport'), icon: FileText, prompt: i18n.t('aiops.opsReportPrompt'), contextLoader: loadReportContext }, + { id: 'optimize', name: i18n.t('aiops.resourceOptAdvice'), icon: TrendingUp, prompt: i18n.t('aiops.capacityPlanPrompt'), contextLoader: loadMetricsContext }, +]; diff --git a/frontend/src/components/aiops/aiops-assistant/types.ts b/frontend/src/components/aiops/aiops-assistant/types.ts new file mode 100644 index 0000000..f303515 --- /dev/null +++ b/frontend/src/components/aiops/aiops-assistant/types.ts @@ -0,0 +1,39 @@ +import type { LLMConfigData } from '@/api'; + +/** 默认 LLM 配置 */ +export const defaultConfig: LLMConfigData = { + provider: 'openai', + model: 'gpt-4o-mini', + api_key: '', + endpoint: 'https://api.openai.com/v1', + temperature: 0.7, + max_tokens: 2000, + system_prompt: '', + enabled: false, + reasoning_enabled: false, +}; + +/** 快捷操作类型(contextLoader 可选,支持未来无数据加载的纯文本操作) */ +export interface QuickAction { + id: string; + name: string; + icon: typeof import('lucide-react').AlertTriangle; + prompt: string; + contextLoader?: () => Promise; +} + +/** 聊天消息类型 */ +export interface Message { + id: string; + role: 'user' | 'assistant'; + content: string; + timestamp: string; + isError?: boolean; + isStopped?: boolean; +} + +/** 格式化时间为 HH:MM */ +export function fmtTime(iso: string): string { + const d = new Date(iso); + return d.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' }); +}