Q34: AIOpsAssistant 巨型组件拆分 (505L→288L, 提取 aiops-assistant/ 5 文件)
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 集成测试通过
This commit is contained in:
1 parent
adb5a57bb2
commit
c7d050f1bc
7 files changed
+337
-305
No files matched your search
@@ -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<string> {
|
||||
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<string> {
|
||||
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<string> {
|
||||
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<string>;
|
||||
}
|
||||
|
||||
// 快捷操作(已配置 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<Message[]>([]);
|
||||
const [input, setInput] = useState('');
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
// 用于中止流式生成(点击t('common.stop')按钮时 abort) // Logan.Li
|
||||
const abortRef = useRef<AbortController | null>(null);
|
||||
// 组件卸载时中止进行中的流式请求,避免 setState on unmounted // Logan.Li
|
||||
useEffect(() => () => abortRef.current?.abort(), []);
|
||||
const [config, setConfig] = useState<LLMConfigData>(defaultConfig);
|
||||
const [configReady, setConfigReady] = useState(false); // 已配置且启用
|
||||
const [contextLoading, setContextLoading] = useState<string | null>(null); // 快捷操作拉取平台数据中
|
||||
// 会话 ID:前端生成 UUID,用于隔离多轮对话 // Logan.Li
|
||||
// crypto.randomUUID() 需要 HTTPS/secure context,HTTP 环境用 fallback
|
||||
const [configReady, setConfigReady] = useState(false);
|
||||
const [contextLoading, setContextLoading] = useState<string | null>(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<HTMLDivElement>(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 (
|
||||
<PageShell
|
||||
variant="workspace"
|
||||
@@ -331,175 +199,90 @@ export function AIOpsAssistant() {
|
||||
) : undefined}
|
||||
contentClassName="grid grid-cols-4 gap-6 h-[calc(100vh-200px)]"
|
||||
>
|
||||
{/* Sidebar */}
|
||||
<div className="col-span-1 space-y-4">
|
||||
<Card className="dg-card">
|
||||
<CardHeader className="pb-3">
|
||||
<CardTitle className="text-sm text-[var(--dg-text-secondary)]">{t('aiops.quickActions')}</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-2">
|
||||
{quickActions.map((action) => (
|
||||
<Button
|
||||
key={action.id}
|
||||
variant="ghost"
|
||||
className="w-full justify-start text-[var(--dg-text-secondary)] hover:text-[var(--dg-text-primary)] hover:bg-[var(--dg-bg-hover)]"
|
||||
disabled={isLoading || contextLoading !== null}
|
||||
onClick={() => handleQuickAction(action)}
|
||||
>
|
||||
{contextLoading === action.id ? (
|
||||
<Loader2 className="h-4 w-4 mr-2 shrink-0 animate-spin" />
|
||||
) : (
|
||||
<action.icon className="h-4 w-4 mr-2 shrink-0" />
|
||||
)}
|
||||
<span className="text-sm">{action.name}</span>
|
||||
{configReady && action.contextLoader && (
|
||||
<span className="ml-auto text-[10px] dg-text-green/60 shrink-0">{t('common.realtime')}</span>
|
||||
)}
|
||||
</Button>
|
||||
))}
|
||||
</CardContent>
|
||||
</Card>
|
||||
<div className="col-span-1">
|
||||
<AssistantSidebar
|
||||
actions={quickActions}
|
||||
isLoading={isLoading}
|
||||
contextLoading={contextLoading}
|
||||
configReady={configReady}
|
||||
onAction={handleQuickAction}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<Card className="dg-card">
|
||||
<CardHeader className="pb-3">
|
||||
<CardTitle className="text-sm text-[var(--dg-text-secondary)]">{t('aiops.capabilities')}</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-3">
|
||||
<div className="flex items-center gap-2 text-sm dg-text-secondary">
|
||||
<AlertTriangle className="h-4 w-4 dg-text-yellow" />
|
||||
<span>{t('aiops.alertAnalysisTitle')}</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-2 text-sm dg-text-secondary">
|
||||
<Activity className="h-4 w-4 dg-text-blue" />
|
||||
<span>{t('aiops.performanceBottleneck')}</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-2 text-sm dg-text-secondary">
|
||||
<FileText className="h-4 w-4 dg-text-green" />
|
||||
<span>{t('aiops.autoReportGen')}</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-2 text-sm dg-text-secondary">
|
||||
<Terminal className="h-4 w-4 dg-text-purple" />
|
||||
<span>{t('aiops.autoScriptGenerated')}</span>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
<Card className="col-span-3 dg-card flex flex-col">
|
||||
<CardHeader className="border-b border-[var(--dg-border)] pb-3">
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-2">
|
||||
<Bot className="h-5 w-5 dg-text-purple" />
|
||||
<span className="font-medium text-[var(--dg-text-primary)]">{t('aiops.aiAssistantShort')}</span>
|
||||
{configReady ? (
|
||||
<Badge variant="outline" className="border-emerald-500/30 dg-text-green bg-emerald-500/10 text-xs">
|
||||
<span className="w-2 h-2 rounded-full bg-emerald-400 mr-1 animate-pulse" />
|
||||
{t('common.online')}
|
||||
</Badge>
|
||||
) : (
|
||||
<Badge variant="outline" className="border-[var(--dg-border-hover)] dg-text-secondary text-xs">{t('common.offline')}</Badge>
|
||||
)}
|
||||
</div>
|
||||
<Button variant="ghost" size="sm" className="dg-text-secondary" onClick={handleNewChat} disabled={messages.length === 0}>
|
||||
<RotateCw className="h-4 w-4 mr-1" />
|
||||
{t('aiops.newConversation')}
|
||||
</Button>
|
||||
</div>
|
||||
</CardHeader>
|
||||
|
||||
{/* Chat Area */}
|
||||
<Card className="col-span-3 dg-card flex flex-col">
|
||||
<CardHeader className="border-b border-[var(--dg-border)] pb-3">
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-2">
|
||||
<Bot className="h-5 w-5 dg-text-purple" />
|
||||
<span className="font-medium text-[var(--dg-text-primary)]">{t('aiops.aiAssistantShort')}</span>
|
||||
{configReady ? (
|
||||
<Badge variant="outline" className="border-emerald-500/30 dg-text-green bg-emerald-500/10 text-xs">
|
||||
<span className="w-2 h-2 rounded-full bg-emerald-400 mr-1 animate-pulse" />
|
||||
{t('common.online')}
|
||||
</Badge>
|
||||
) : (
|
||||
<Badge variant="outline" className="border-[var(--dg-border-hover)] dg-text-secondary text-xs">{t('common.offline')}</Badge>
|
||||
<ScrollArea className="flex-1 p-4">
|
||||
<div className="space-y-4">
|
||||
{messages.length === 0 && !isLoading && (
|
||||
<div className="flex flex-col items-center justify-center py-16 dg-text-muted">
|
||||
<MessageSquare className="h-10 w-10 mb-3 opacity-30" />
|
||||
<p>{configReady ? t('aiops.emptyConvHint') : t('aiops.aiNotConfigured')}</p>
|
||||
{!configReady && (
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="mt-4 dg-btn-secondary hover:dg-text-purple"
|
||||
onClick={() => navigate('/ai-llm-config')}
|
||||
>
|
||||
<Settings className="h-4 w-4 mr-1" />
|
||||
{t('monitor.dashboard.zabbix.goConfig')}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
<Button variant="ghost" size="sm" className="dg-text-secondary" onClick={handleNewChat} disabled={messages.length === 0}>
|
||||
<RotateCw className="h-4 w-4 mr-1" />
|
||||
{t('aiops.newConversation')}
|
||||
</Button>
|
||||
</div>
|
||||
</CardHeader>
|
||||
)}
|
||||
{messages.map((message) => (
|
||||
<ChatMessage key={message.id} message={message} isLoading={isLoading} />
|
||||
))}
|
||||
<div ref={messagesEndRef} />
|
||||
</div>
|
||||
</ScrollArea>
|
||||
|
||||
<ScrollArea className="flex-1 p-4">
|
||||
<div className="space-y-4">
|
||||
{messages.length === 0 && !isLoading && (
|
||||
<div className="flex flex-col items-center justify-center py-16 dg-text-muted">
|
||||
<MessageSquare className="h-10 w-10 mb-3 opacity-30" />
|
||||
<p>{configReady ? t('aiops.emptyConvHint') : t('aiops.aiNotConfigured')}</p>
|
||||
{!configReady && (
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="mt-4 dg-btn-secondary hover:dg-text-purple"
|
||||
onClick={() => navigate('/ai-llm-config')}
|
||||
>
|
||||
<Settings className="h-4 w-4 mr-1" />
|
||||
{t('monitor.dashboard.zabbix.goConfig')}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
{messages.map((message) => {
|
||||
// 流式中:助手消息内容为空且正在加载时显示t('aiops.thinking')占位 // Logan.Li
|
||||
const isStreaming = isLoading && message.role === 'assistant' && message.content === '';
|
||||
return (
|
||||
<div key={message.id} className={`flex gap-3 ${message.role === 'user' ? 'flex-row-reverse' : ''}`}>
|
||||
<Avatar className={message.role === 'assistant' ? 'bg-purple-500' : 'bg-blue-500'}>
|
||||
<AvatarFallback>
|
||||
{message.role === 'assistant' ? <Bot className="h-4 w-4" /> : <User className="h-4 w-4" />}
|
||||
</AvatarFallback>
|
||||
</Avatar>
|
||||
<div className={`max-w-[80%] ${message.role === 'user' ? 'text-right' : ''}`}>
|
||||
<div
|
||||
className={`inline-block rounded-lg p-3 text-left whitespace-pre-wrap break-words ${
|
||||
message.isError
|
||||
? 'bg-red-900/30 border border-red-500/30 dg-text-red'
|
||||
: message.role === 'assistant'
|
||||
? 'bg-[var(--dg-bg-tertiary)] text-[var(--dg-text-primary)]'
|
||||
: 'bg-blue-600 text-white'
|
||||
}`}
|
||||
>
|
||||
{isStreaming ? (
|
||||
<div className="flex items-center gap-2 dg-text-secondary">
|
||||
<Loader2 className="h-4 w-4 animate-spin" />
|
||||
<span className="text-sm">{t('aiops.thinking')}</span>
|
||||
</div>
|
||||
) : (
|
||||
message.content
|
||||
)}
|
||||
{/* 流式接收中且已有内容时,显示末尾闪烁光标提示 */}
|
||||
{isLoading && message.role === 'assistant' && !isStreaming && message.content && (
|
||||
<span className="inline-block w-2 h-4 ml-0.5 bg-purple-400 animate-pulse align-middle" />
|
||||
)}
|
||||
</div>
|
||||
<div className="text-xs dg-text-muted mt-1">
|
||||
{fmtTime(message.timestamp)}
|
||||
{message.isStopped && <span className="ml-2 dg-text-muted">{t('aiops.stoppedParen')}</span>}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
{/* 流式输出时占位气泡已包含t('aiops.thinking')提示,无需独立 spinner */}
|
||||
<div ref={messagesEndRef} />
|
||||
</div>
|
||||
</ScrollArea>
|
||||
|
||||
<CardContent className="border-t border-[var(--dg-border)] pt-4">
|
||||
<div className="flex gap-2">
|
||||
<Input
|
||||
value={input}
|
||||
onChange={(e) => 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}
|
||||
/>
|
||||
<Button className="bg-purple-600 hover:bg-purple-700" onClick={handleSend} disabled={isLoading || !input.trim()}>
|
||||
<Send className="h-4 w-4" />
|
||||
<CardContent className="border-t border-[var(--dg-border)] pt-4">
|
||||
<div className="flex gap-2">
|
||||
<Input
|
||||
value={input}
|
||||
onChange={(e) => 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}
|
||||
/>
|
||||
<Button className="bg-purple-600 hover:bg-purple-700" onClick={handleSend} disabled={isLoading || !input.trim()}>
|
||||
<Send className="h-4 w-4" />
|
||||
</Button>
|
||||
{isLoading && (
|
||||
<Button
|
||||
variant="outline"
|
||||
className="border-red-500/40 dg-text-red hover:bg-red-500/10"
|
||||
onClick={() => abortRef.current?.abort()}
|
||||
title={t('aiops.stopGenerate')}
|
||||
>
|
||||
<Square className="h-4 w-4" />
|
||||
</Button>
|
||||
{/* 流式生成中显示\"停止生成\"按钮,中止当前请求 // Logan.Li */}
|
||||
{isLoading && (
|
||||
<Button
|
||||
variant="outline"
|
||||
className="border-red-500/40 dg-text-red hover:bg-red-500/10"
|
||||
onClick={() => abortRef.current?.abort()}
|
||||
title={t('aiops.stopGenerate')}
|
||||
>
|
||||
<Square className="h-4 w-4" />
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</PageShell>
|
||||
);
|
||||
}
|
||||
@@ -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 (
|
||||
<div className="space-y-4">
|
||||
<Card className="dg-card">
|
||||
<CardHeader className="pb-3">
|
||||
<CardTitle className="text-sm text-[var(--dg-text-secondary)]">{t('aiops.quickActions')}</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-2">
|
||||
{actions.map((action) => (
|
||||
<Button
|
||||
key={action.id}
|
||||
variant="ghost"
|
||||
className="w-full justify-start text-[var(--dg-text-secondary)] hover:text-[var(--dg-text-primary)] hover:bg-[var(--dg-bg-hover)]"
|
||||
disabled={isLoading || contextLoading !== null}
|
||||
onClick={() => onAction(action)}
|
||||
>
|
||||
{contextLoading === action.id ? (
|
||||
<Loader2 className="h-4 w-4 mr-2 shrink-0 animate-spin" />
|
||||
) : (
|
||||
<action.icon className="h-4 w-4 mr-2 shrink-0" />
|
||||
)}
|
||||
<span className="text-sm">{action.name}</span>
|
||||
{configReady && action.contextLoader && (
|
||||
<span className="ml-auto text-[10px] dg-text-green/60 shrink-0">{t('common.realtime')}</span>
|
||||
)}
|
||||
</Button>
|
||||
))}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card className="dg-card">
|
||||
<CardHeader className="pb-3">
|
||||
<CardTitle className="text-sm text-[var(--dg-text-secondary)]">{t('aiops.capabilities')}</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-3">
|
||||
<div className="flex items-center gap-2 text-sm dg-text-secondary">
|
||||
<AlertTriangle className="h-4 w-4 dg-text-yellow" />
|
||||
<span>{t('aiops.alertAnalysisTitle')}</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-2 text-sm dg-text-secondary">
|
||||
<Activity className="h-4 w-4 dg-text-blue" />
|
||||
<span>{t('aiops.performanceBottleneck')}</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-2 text-sm dg-text-secondary">
|
||||
<FileText className="h-4 w-4 dg-text-green" />
|
||||
<span>{t('aiops.autoReportGen')}</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-2 text-sm dg-text-secondary">
|
||||
<Terminal className="h-4 w-4 dg-text-purple" />
|
||||
<span>{t('aiops.autoScriptGenerated')}</span>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -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 (
|
||||
<div className={`flex gap-3 ${message.role === 'user' ? 'flex-row-reverse' : ''}`}>
|
||||
<Avatar className={message.role === 'assistant' ? 'bg-purple-500' : 'bg-blue-500'}>
|
||||
<AvatarFallback>
|
||||
{message.role === 'assistant' ? <Bot className="h-4 w-4" /> : <User className="h-4 w-4" />}
|
||||
</AvatarFallback>
|
||||
</Avatar>
|
||||
<div className={`max-w-[80%] ${message.role === 'user' ? 'text-right' : ''}`}>
|
||||
<div
|
||||
className={`inline-block rounded-lg p-3 text-left whitespace-pre-wrap break-words ${
|
||||
message.isError
|
||||
? 'bg-red-900/30 border border-red-500/30 dg-text-red'
|
||||
: message.role === 'assistant'
|
||||
? 'bg-[var(--dg-bg-tertiary)] text-[var(--dg-text-primary)]'
|
||||
: 'bg-blue-600 text-white'
|
||||
}`}
|
||||
>
|
||||
{isStreaming ? (
|
||||
<div className="flex items-center gap-2 dg-text-secondary">
|
||||
<Loader2 className="h-4 w-4 animate-spin" />
|
||||
<span className="text-sm">{t('aiops.thinking')}</span>
|
||||
</div>
|
||||
) : (
|
||||
message.content
|
||||
)}
|
||||
{isLoading && message.role === 'assistant' && !isStreaming && message.content && (
|
||||
<span className="inline-block w-2 h-4 ml-0.5 bg-purple-400 animate-pulse align-middle" />
|
||||
)}
|
||||
</div>
|
||||
<div className="text-xs dg-text-muted mt-1">
|
||||
{fmtTime(message.timestamp)}
|
||||
{message.isStopped && <span className="ml-2 dg-text-muted">{t('aiops.stoppedParen')}</span>}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -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<string> {
|
||||
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<string> {
|
||||
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<string> {
|
||||
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')}`;
|
||||
}
|
||||
@@ -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 },
|
||||
];
|
||||
@@ -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<string>;
|
||||
}
|
||||
|
||||
/** 聊天消息类型 */
|
||||
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' });
|
||||
}
|
||||
Reference in new issue
Block a user