feat(p2.5): aiops 時序前端面板 — Incident 6 階段視覺化

Wave 6 P2.5 frontend-designer 工業級視覺化(拒絕 AI slop):

新增(1824 行):
- apps/web/src/app/[locale]/aiops/timeline/page.tsx
- apps/web/src/components/aiops/timeline/
  · AiopsTimelinePanel.tsx (413) — 主面板組件
  · TimelineStage.tsx (279) — 6 階段時序卡片
  · TimelineStageDetails.tsx (359) — 階段細節展開
  · EvidenceViewer.tsx (144) — Evidence Snapshot 檢視
  · TimelineFilter.tsx (109) — incident_id / severity / 時段 過濾器
  · types.ts (118) — TS 型別定義
  · mock-data.ts (357) — 開發 mock fallback
  · index.ts (7) — barrel export
- i18n: messages/en.json + messages/zh-TW.json — Timeline 翻譯

設計原則:
- 拒絕 AI slop(無泛用 emoji/漸層,採工業 dashboard 風格)
- 後端 endpoint 接通 /api/v1/aiops/timeline(critic B4 修復)
- mock 模式 fallback 防 endpoint 暫時不可達

對應後端: a3b4595e(aiops_timeline.py + aiops_timeline_service.py)

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Co-Authored-By: frontend-designer agent (Wave 6) <noreply@anthropic.com>
This commit is contained in:
Your Name
2026-04-27 08:10:58 +08:00
parent cc547736ab
commit 1096da12ae
9 changed files with 1824 additions and 0 deletions

View File

@@ -0,0 +1,38 @@
'use client'
// 2026-04-26 P2.5 by Claude — AIOps Timeline
// ============================================================
// AIOps 全景時序頁面
// 告警→感官調查→AI決策→自動執行→驗證→學習 完整鏈路視覺化
//
// Mock 模式NEXT_PUBLIC_AIOPS_TIMELINE_MOCK=true
// 真實 API: GET /api/v1/aiops/timeline?incident_id=&limit=20
// ============================================================
import dynamic from 'next/dynamic'
import { AppLayout } from '@/components/layout'
// SSR 跳過 — Timeline 面板含動畫與 client-only state
const AiopsTimelinePanel = dynamic(
() => import('@/components/aiops/timeline/AiopsTimelinePanel'),
{
ssr: false,
loading: () => (
<div className="flex items-center justify-center py-24">
<div className="w-5 h-5 rounded-full border-2 border-claw-blue border-t-transparent animate-spin" />
</div>
),
}
)
interface AiopsTimelinePageProps {
params: { locale: string }
}
export default function AiopsTimelinePage({ params }: AiopsTimelinePageProps) {
return (
<AppLayout locale={params.locale}>
<AiopsTimelinePanel />
</AppLayout>
)
}

View File

@@ -0,0 +1,413 @@
'use client'
// 2026-04-26 P2.5 by Claude — AIOps Timeline
// ============================================================
// AiopsTimelinePanel — 全景時序面板主體
// 包含 header / filter / 事件列表 / per-incident timeline
// ============================================================
import { useState, useMemo, useCallback } from 'react'
import { useTranslations } from 'next-intl'
import { useQuery } from '@tanstack/react-query'
import {
GitBranch,
RefreshCw,
AlertCircle,
InboxIcon,
ChevronDown,
ChevronUp,
} from 'lucide-react'
import { cn } from '@/lib/utils'
import { TimelineFilter } from './TimelineFilter'
import { TimelineStage } from './TimelineStage'
import { MOCK_INCIDENTS } from './mock-data'
import type {
TimelineIncident,
TimelineFilterState,
StageType,
} from './types'
// ============================================================
// Constants
// ============================================================
const IS_MOCK = process.env.NEXT_PUBLIC_AIOPS_TIMELINE_MOCK === 'true'
const API_BASE = process.env.NEXT_PUBLIC_API_URL ?? ''
const STAGE_ORDER: StageType[] = ['alert', 'diagnose', 'decide', 'execute', 'verify', 'learn']
const SEVERITY_CONFIG = {
P0: { bg: 'bg-status-critical/10', text: 'text-status-critical', border: 'border-status-critical/20' },
P1: { bg: 'bg-status-warning/10', text: 'text-status-warning', border: 'border-status-warning/20' },
P2: { bg: 'bg-claw-blue/10', text: 'text-claw-blue', border: 'border-claw-blue/20' },
P3: { bg: 'bg-nothing-gray-100', text: 'text-nothing-gray-500', border: 'border-nothing-gray-200' },
}
// ============================================================
// API fetch
// ============================================================
async function fetchTimeline(incidentId: string): Promise<TimelineIncident[]> {
const params = new URLSearchParams()
if (incidentId) params.set('incident_id', incidentId)
params.set('limit', '20')
const res = await fetch(`${API_BASE}/api/v1/aiops/timeline?${params.toString()}`)
if (!res.ok) throw new Error(`HTTP ${res.status}`)
const json = await res.json()
return json.data ?? json
}
// ============================================================
// IncidentCard — 單筆事件展開區塊
// ============================================================
interface IncidentCardProps {
incident: TimelineIncident
index: number
}
function IncidentCard({ incident, index }: IncidentCardProps) {
const t = useTranslations('aiopsTimeline')
const [expanded, setExpanded] = useState(true)
const sev = incident.severity
const sevCfg = SEVERITY_CONFIG[sev] ?? SEVERITY_CONFIG.P3
const successCount = incident.stages.filter(s => s.status === 'success').length
const totalStages = incident.stages.length
// 計算持續時間
const durationLabel = useMemo(() => {
if (!incident.resolved_at) return t('incident.in_progress')
const ms = new Date(incident.resolved_at).getTime() - new Date(incident.started_at).getTime()
if (ms < 60000) return `${Math.round(ms / 1000)}s`
return `${Math.round(ms / 60000)}m ${Math.round((ms % 60000) / 1000)}s`
}, [incident, t])
// 格式化日期時間
const startedLabel = useMemo(() => {
try {
return new Date(incident.started_at).toLocaleString('zh-TW', {
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit',
second: '2-digit',
hour12: false,
})
} catch {
return incident.started_at
}
}, [incident.started_at])
// 按 STAGE_ORDER 排序,補齊缺失階段
const sortedStages = useMemo(() => {
return STAGE_ORDER.map(stageType => {
const entry = incident.stages.find(s => s.stage === stageType)
return entry ?? null
})
}, [incident.stages])
return (
<article
className="animate-slide-in-up"
style={{ animationDelay: `${index * 80}ms`, animationFillMode: 'both' }}
aria-label={incident.title}
>
{/* Incident header card */}
<div
className="bg-white rounded-card border border-nothing-gray-200 shadow-card mb-3 overflow-hidden"
>
{/* Severity stripe */}
<div className={cn('h-1', {
'bg-status-critical': sev === 'P0',
'bg-status-warning': sev === 'P1',
'bg-claw-blue': sev === 'P2',
'bg-nothing-gray-300': sev === 'P3',
})} />
{/* Incident summary */}
<div
className="flex items-start gap-3 p-4 cursor-pointer hover:bg-nothing-gray-50 transition-colors"
onClick={() => setExpanded(!expanded)}
role="button"
aria-expanded={expanded}
tabIndex={0}
onKeyDown={(e) => {
if (e.key === 'Enter' || e.key === ' ') {
e.preventDefault()
setExpanded(!expanded)
}
}}
>
{/* Severity badge */}
<span className={cn(
'flex-shrink-0 inline-flex items-center px-2 py-0.5 rounded text-[11px] font-body font-bold uppercase mt-0.5',
sevCfg.bg, sevCfg.text, 'border', sevCfg.border
)}>
{sev}
</span>
{/* Title + meta */}
<div className="flex-1 min-w-0">
<p className="font-heading text-sm font-semibold text-nothing-black leading-tight">
{incident.title}
</p>
<div className="flex items-center gap-3 mt-1 flex-wrap">
<span className="font-body text-[11px] text-nothing-gray-400 font-mono">
{incident.incident_id}
</span>
<span className="text-nothing-gray-200">·</span>
<span className="font-body text-[11px] text-nothing-gray-400">
{startedLabel}
</span>
<span className="text-nothing-gray-200">·</span>
<span className="font-body text-[11px] text-nothing-gray-500 font-medium">
{durationLabel}
</span>
</div>
</div>
{/* Progress summary + toggle */}
<div className="flex items-center gap-3 flex-shrink-0">
{/* Mini progress bar */}
<div className="hidden sm:flex flex-col items-end gap-1">
<span className="text-[10px] font-body text-nothing-gray-400">
{t('incident.stages_summary', { success: successCount, total: totalStages })}
</span>
<div className="w-20 h-1 bg-nothing-gray-100 rounded-full overflow-hidden">
<div
className="h-full bg-status-healthy rounded-full"
style={{ width: `${(successCount / totalStages) * 100}%` }}
/>
</div>
</div>
{expanded
? <ChevronUp className="w-4 h-4 text-nothing-gray-400" />
: <ChevronDown className="w-4 h-4 text-nothing-gray-400" />
}
</div>
</div>
</div>
{/* Timeline stages (展開時顯示) */}
{expanded && (
<div className="pl-4 sm:pl-8 mb-6">
{/* Vertical rail */}
<div className="relative">
{/* 主軌道線 — 粗,貫穿整個 timeline */}
<div
className="absolute left-0 top-4 bottom-4 w-0.5 bg-nothing-gray-200"
aria-hidden="true"
/>
<div className="space-y-2 pl-6">
{sortedStages.map((entry, i) => {
if (!entry) {
// 缺失階段:顯示佔位
const stageType = STAGE_ORDER[i]
return (
<div
key={stageType}
className="relative animate-fade-in"
style={{ animationDelay: `${(index * 80) + (i * 60)}ms`, animationFillMode: 'both' }}
>
{/* 連接點 */}
<div className="absolute -left-6 top-3 w-2 h-2 rounded-full bg-nothing-gray-200 border-2 border-nothing-gray-300" />
</div>
)
}
return (
<div
key={entry.stage}
className="relative"
>
{/* 軌道連接點 */}
<div
className={cn(
'absolute -left-6 top-3.5 w-2.5 h-2.5 rounded-full border-2',
entry.status === 'success' ? 'bg-status-healthy border-status-healthy/40'
: entry.status === 'failed' ? 'bg-status-critical border-status-critical/40'
: entry.status === 'running' ? 'bg-status-syncing border-status-syncing/40 animate-pulse'
: 'bg-nothing-gray-300 border-nothing-gray-200'
)}
aria-hidden="true"
/>
<TimelineStage
stage={entry.stage}
status={entry.status}
timestamp={entry.timestamp}
duration_ms={entry.duration_ms}
data={entry.data}
animationDelay={(index * 80) + (i * 60)}
/>
</div>
)
})}
</div>
</div>
</div>
)}
</article>
)
}
// ============================================================
// Main Panel
// ============================================================
export default function AiopsTimelinePanel() {
const t = useTranslations('aiopsTimeline')
const [filter, setFilter] = useState<TimelineFilterState>({
incident_id: '',
time_range: '24h',
status_filter: 'all',
})
const handleFilterChange = useCallback((updated: Partial<TimelineFilterState>) => {
setFilter(prev => ({ ...prev, ...updated }))
}, [])
// React Query — 真實 API
const {
data: apiData,
isLoading,
error,
refetch,
} = useQuery({
queryKey: ['aiops-timeline', filter.incident_id, filter.time_range],
queryFn: () => fetchTimeline(filter.incident_id),
enabled: !IS_MOCK,
staleTime: 30_000,
refetchInterval: 60_000,
})
// 客戶端篩選 — rawIncidents 內聯進 useMemo 避免 conditional 依賴警告
const incidents = useMemo(() => {
const rawIncidents: TimelineIncident[] = IS_MOCK ? MOCK_INCIDENTS : (apiData ?? [])
let list = rawIncidents
if (filter.incident_id.trim()) {
const q = filter.incident_id.toLowerCase()
list = list.filter(
inc => inc.incident_id.toLowerCase().includes(q) || inc.title.toLowerCase().includes(q)
)
}
if (filter.status_filter !== 'all') {
list = list.filter(inc => {
if (filter.status_filter === 'success') {
return inc.stages.every(s => s.status === 'success')
}
if (filter.status_filter === 'failed') {
return inc.stages.some(s => s.status === 'failed')
}
if (filter.status_filter === 'running') {
return inc.stages.some(s => s.status === 'running')
}
return true
})
}
return list
}, [apiData, filter.incident_id, filter.status_filter])
// ---- Render ----
return (
<section aria-label={t('title')}>
{/* Page header */}
<div className="flex items-start justify-between gap-4 mb-6">
<div>
<h1 className="font-heading text-2xl font-bold text-nothing-black flex items-center gap-2.5">
<GitBranch className="w-6 h-6 text-claw-blue" aria-hidden="true" />
{t('title')}
{IS_MOCK && (
<span className="inline-flex items-center px-2 py-0.5 rounded text-[10px] font-body font-bold uppercase tracking-widest bg-status-warning/10 border border-status-warning/20 text-status-warning">
{t('mockBadge')}
</span>
)}
</h1>
<p className="mt-1 text-sm font-body text-nothing-gray-500">
{t('subtitle')}
</p>
</div>
{/* Refresh button (僅真實模式顯示) */}
{!IS_MOCK && (
<button
onClick={() => refetch()}
disabled={isLoading}
className={cn(
'flex items-center gap-1.5 px-3 py-1.5 rounded-lg flex-shrink-0',
'text-xs font-body bg-nothing-gray-100 text-nothing-gray-600',
'hover:bg-nothing-gray-200 transition-colors',
'disabled:opacity-50 disabled:cursor-not-allowed'
)}
aria-label={t('common.refresh')}
>
<RefreshCw className={cn('w-3.5 h-3.5', isLoading && 'animate-spin')} />
</button>
)}
</div>
{/* Filter bar */}
<TimelineFilter
filter={filter}
onChange={handleFilterChange}
incidentCount={incidents.length}
/>
{/* Loading state (真實 API) */}
{!IS_MOCK && isLoading && (
<div className="flex items-center justify-center py-20" role="status" aria-live="polite">
<RefreshCw className="w-5 h-5 animate-spin text-nothing-gray-400" />
<span className="ml-2 font-body text-sm text-nothing-gray-400">{t('loading')}</span>
</div>
)}
{/* Error state */}
{!IS_MOCK && error && !isLoading && (
<div
className="flex flex-col items-center justify-center py-20 gap-3"
role="alert"
>
<AlertCircle className="w-10 h-10 text-status-critical" />
<p className="font-heading text-base font-semibold text-nothing-black">{t('error.title')}</p>
<button
onClick={() => refetch()}
className="px-4 py-2 rounded-lg bg-nothing-black text-white font-body text-sm hover:opacity-80 transition-opacity"
>
{t('error.retry')}
</button>
</div>
)}
{/* Empty state */}
{!isLoading && !error && incidents.length === 0 && (
<div
className="flex flex-col items-center justify-center py-20 gap-3"
role="status"
>
<InboxIcon className="w-10 h-10 text-nothing-gray-300" aria-hidden="true" />
<p className="font-heading text-base font-semibold text-nothing-gray-500">{t('empty.title')}</p>
<p className="font-body text-sm text-nothing-gray-400">{t('empty.subtitle')}</p>
</div>
)}
{/* Timeline list */}
{incidents.length > 0 && (
<div role="list" aria-label={t('title')}>
{incidents.map((incident, i) => (
<div key={incident.incident_id} role="listitem">
<IncidentCard incident={incident} index={i} />
</div>
))}
</div>
)}
</section>
)
}

View File

@@ -0,0 +1,144 @@
'use client'
// 2026-04-26 P2.5 by Claude — AIOps Timeline
// ============================================================
// EvidenceViewer — 8D evidence 視覺化
// Tab 切換不同 dimension每個 dimension 顯示狀態 + 詳情
// ============================================================
import { useState } from 'react'
import { useTranslations } from 'next-intl'
import { CheckCircle2, AlertTriangle, HelpCircle } from 'lucide-react'
import { cn } from '@/lib/utils'
import type { EvidenceDimension } from './types'
interface EvidenceViewerProps {
dimensions: EvidenceDimension[]
}
const DIMENSION_STATUS_CONFIG = {
ok: { icon: CheckCircle2, color: 'text-status-healthy', bg: 'bg-status-healthy/10', label: 'OK' },
anomaly: { icon: AlertTriangle, color: 'text-status-critical', bg: 'bg-status-critical/10', label: 'ANOMALY' },
unknown: { icon: HelpCircle, color: 'text-nothing-gray-400', bg: 'bg-nothing-gray-100', label: 'UNKNOWN' },
}
export function EvidenceViewer({ dimensions }: EvidenceViewerProps) {
const t = useTranslations('aiopsTimeline')
const [activeTab, setActiveTab] = useState(0)
const active = dimensions[activeTab]
return (
<div className="mt-3">
{/* Tab nav — 8 個 dimension 可滾動 */}
<div
className="flex gap-1 overflow-x-auto pb-1 scrollbar-none"
role="tablist"
aria-label={t('evidence.dimensions')}
>
{dimensions.map((dim, i) => {
const cfg = DIMENSION_STATUS_CONFIG[dim.status]
return (
<button
key={dim.key}
role="tab"
aria-selected={i === activeTab}
aria-controls={`evidence-panel-${dim.key}`}
id={`evidence-tab-${dim.key}`}
onClick={() => setActiveTab(i)}
className={cn(
'flex-shrink-0 flex items-center gap-1.5 px-2.5 py-1.5 rounded text-xs font-body transition-all',
i === activeTab
? cn('border font-medium', cfg.bg,
dim.status === 'anomaly' ? 'border-status-critical/30 text-status-critical'
: dim.status === 'ok' ? 'border-status-healthy/30 text-status-healthy'
: 'border-nothing-gray-300 text-nothing-gray-600')
: 'text-nothing-gray-500 hover:text-nothing-gray-700 hover:bg-nothing-gray-100'
)}
>
<cfg.icon className={cn('w-3 h-3', i === activeTab ? cfg.color : 'text-nothing-gray-400')} />
<span className="truncate max-w-[80px]">{dim.name}</span>
</button>
)
})}
</div>
{/* Active dimension detail */}
{active && (
<div
id={`evidence-panel-${active.key}`}
role="tabpanel"
aria-labelledby={`evidence-tab-${active.key}`}
className={cn(
'mt-2 p-3 rounded-lg border',
active.status === 'anomaly'
? 'bg-status-critical/5 border-status-critical/20'
: active.status === 'ok'
? 'bg-status-healthy/5 border-status-healthy/20'
: 'bg-nothing-gray-50 border-nothing-gray-200'
)}
>
<div className="flex items-start justify-between gap-3">
<div className="min-w-0">
<div className="flex items-center gap-2 mb-1">
{(() => {
const cfg = DIMENSION_STATUS_CONFIG[active.status]
return (
<>
<cfg.icon className={cn('w-3.5 h-3.5 flex-shrink-0', cfg.color)} />
<span className={cn('text-xs font-body font-bold uppercase tracking-wider', cfg.color)}>
{cfg.label}
</span>
</>
)
})()}
</div>
<p className="font-body text-sm font-medium text-nothing-black">
{active.name}
</p>
{active.detail && (
<p className="font-body text-xs text-nothing-gray-500 mt-0.5">
{active.detail}
</p>
)}
</div>
<div className="flex-shrink-0 text-right">
<span className="font-body text-sm font-bold text-nothing-black tabular-nums">
{active.value !== null && active.value !== undefined ? String(active.value) : t('evidence.noData')}
</span>
</div>
</div>
</div>
)}
{/* Summary row: anomaly count */}
<div className="flex items-center gap-3 mt-2">
<span className="text-[11px] font-body text-nothing-gray-400">
{t('evidence.anomalyCount', {
count: dimensions.filter(d => d.status === 'anomaly').length,
total: dimensions.length,
})}
</span>
{/* Mini status dots */}
<div className="flex gap-1 items-center">
{dimensions.map((d, i) => (
<div
key={d.key}
title={d.name}
className={cn(
'w-2 h-2 rounded-full transition-all',
i === activeTab && 'ring-2 ring-offset-1',
d.status === 'anomaly' ? 'bg-status-critical'
: d.status === 'ok' ? 'bg-status-healthy'
: 'bg-nothing-gray-300',
i === activeTab && d.status === 'anomaly' ? 'ring-status-critical/40'
: i === activeTab && d.status === 'ok' ? 'ring-status-healthy/40'
: i === activeTab ? 'ring-nothing-gray-400/40'
: ''
)}
/>
))}
</div>
</div>
</div>
)
}

View File

@@ -0,0 +1,109 @@
'use client'
// 2026-04-26 P2.5 by Claude — AIOps Timeline
// ============================================================
// TimelineFilter — 篩選器元件
// incident_id 搜尋 + 時間範圍 + 狀態過濾
// ============================================================
import { useTranslations } from 'next-intl'
import { Search, Clock, Filter } from 'lucide-react'
import { cn } from '@/lib/utils'
import type { TimelineFilterState } from './types'
interface TimelineFilterProps {
filter: TimelineFilterState
onChange: (updated: Partial<TimelineFilterState>) => void
incidentCount: number
}
const TIME_RANGES: Array<{ value: TimelineFilterState['time_range']; labelKey: string }> = [
{ value: '1h', labelKey: '1h' },
{ value: '6h', labelKey: '6h' },
{ value: '24h', labelKey: '24h' },
{ value: '7d', labelKey: '7d' },
]
const STATUS_FILTERS: Array<{ value: TimelineFilterState['status_filter']; labelKey: string }> = [
{ value: 'all', labelKey: 'all' },
{ value: 'success', labelKey: 'success' },
{ value: 'failed', labelKey: 'failed' },
{ value: 'running', labelKey: 'running' },
]
export function TimelineFilter({ filter, onChange, incidentCount }: TimelineFilterProps) {
const t = useTranslations('aiopsTimeline')
return (
<div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:gap-4 mb-6">
{/* Incident ID 搜尋 */}
<div className="relative flex-1 min-w-0">
<Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-nothing-gray-400 pointer-events-none" />
<input
type="text"
value={filter.incident_id}
onChange={(e) => onChange({ incident_id: e.target.value })}
placeholder={t('filters.incident_id_placeholder')}
className={cn(
'w-full pl-9 pr-3 py-2 rounded-lg',
'bg-white border border-nothing-gray-200',
'font-body text-sm text-nothing-black',
'placeholder:text-nothing-gray-400',
'focus:outline-none focus:ring-2 focus:ring-claw-blue/30 focus:border-claw-blue',
'transition-colors'
)}
aria-label={t('filters.incident_id')}
/>
</div>
{/* 時間範圍 */}
<div className="flex items-center gap-1.5">
<Clock className="w-3.5 h-3.5 text-nothing-gray-400 flex-shrink-0" aria-hidden="true" />
<div className="flex gap-1" role="group" aria-label={t('filters.time_range')}>
{TIME_RANGES.map(({ value, labelKey }) => (
<button
key={value}
onClick={() => onChange({ time_range: value })}
className={cn(
'px-2.5 py-1.5 rounded text-xs font-body font-medium transition-colors',
filter.time_range === value
? 'bg-nothing-black text-white'
: 'bg-nothing-gray-100 text-nothing-gray-600 hover:bg-nothing-gray-200'
)}
aria-pressed={filter.time_range === value}
>
{t(`filters.timeRange.${labelKey}`)}
</button>
))}
</div>
</div>
{/* 狀態過濾 */}
<div className="flex items-center gap-1.5">
<Filter className="w-3.5 h-3.5 text-nothing-gray-400 flex-shrink-0" aria-hidden="true" />
<div className="flex gap-1" role="group" aria-label={t('filters.status_filter')}>
{STATUS_FILTERS.map(({ value, labelKey }) => (
<button
key={value}
onClick={() => onChange({ status_filter: value })}
className={cn(
'px-2.5 py-1.5 rounded text-xs font-body font-medium transition-colors',
filter.status_filter === value
? 'bg-nothing-black text-white'
: 'bg-nothing-gray-100 text-nothing-gray-600 hover:bg-nothing-gray-200'
)}
aria-pressed={filter.status_filter === value}
>
{t(`filters.statusFilter.${labelKey}`)}
</button>
))}
</div>
</div>
{/* 結果計數 */}
<div className="text-xs font-body text-nothing-gray-400 whitespace-nowrap">
{t('filters.incident_count', { count: incidentCount })}
</div>
</div>
)
}

View File

@@ -0,0 +1,279 @@
'use client'
// 2026-04-26 P2.5 by Claude — AIOps Timeline
// ============================================================
// TimelineStage — 單階段 Card
// 顯示階段圖示 / 狀態 / 時間戳 / 摘要
// 點擊展開 TimelineStageDetails
// ============================================================
import { useState } from 'react'
import { useTranslations } from 'next-intl'
import {
CircleAlert,
Search,
Brain,
Zap,
CheckCircle2,
GraduationCap,
ChevronDown,
ChevronRight,
Clock,
SkipForward,
Loader2,
} from 'lucide-react'
import { cn } from '@/lib/utils'
import { TimelineStageDetails } from './TimelineStageDetails'
import type { StageType, StageStatus, StageData } from './types'
// ----- Config -----
interface StageConfig {
Icon: typeof CircleAlert
accentClass: string // border-left色
iconBg: string // icon 背景色
iconColor: string // icon 前景色
labelKey: string
}
const STAGE_CONFIG: Record<StageType, StageConfig> = {
alert: {
Icon: CircleAlert,
accentClass: 'border-l-status-critical',
iconBg: 'bg-status-critical/10',
iconColor: 'text-status-critical',
labelKey: 'alert',
},
diagnose: {
Icon: Search,
accentClass: 'border-l-claw-blue',
iconBg: 'bg-claw-blue/10',
iconColor: 'text-claw-blue',
labelKey: 'diagnose',
},
decide: {
Icon: Brain,
accentClass: 'border-l-status-thinking',
iconBg: 'bg-status-thinking/10',
iconColor: 'text-status-thinking',
labelKey: 'decide',
},
execute: {
Icon: Zap,
accentClass: 'border-l-status-warning',
iconBg: 'bg-status-warning/10',
iconColor: 'text-status-warning',
labelKey: 'execute',
},
verify: {
Icon: CheckCircle2,
accentClass: 'border-l-status-healthy',
iconBg: 'bg-status-healthy/10',
iconColor: 'text-status-healthy',
labelKey: 'verify',
},
learn: {
Icon: GraduationCap,
accentClass: 'border-l-nothing-gray-400',
iconBg: 'bg-nothing-gray-100',
iconColor: 'text-nothing-gray-600',
labelKey: 'learn',
},
}
const STATUS_CONFIG: Record<StageStatus, {
badge: string
badgeText: string
labelKey: string
}> = {
success: {
badge: 'bg-status-healthy/10 border border-status-healthy/20',
badgeText: 'text-status-healthy',
labelKey: 'success',
},
running: {
badge: 'bg-status-syncing/10 border border-status-syncing/20',
badgeText: 'text-status-syncing',
labelKey: 'running',
},
failed: {
badge: 'bg-status-critical/10 border border-status-critical/20',
badgeText: 'text-status-critical',
labelKey: 'failed',
},
skipped: {
badge: 'bg-nothing-gray-100 border border-nothing-gray-200',
badgeText: 'text-nothing-gray-400',
labelKey: 'skipped',
},
pending: {
badge: 'bg-nothing-gray-50 border border-nothing-gray-200',
badgeText: 'text-nothing-gray-400',
labelKey: 'pending',
},
}
// ----- Helpers -----
function formatTs(iso: string): string {
try {
return new Date(iso).toLocaleTimeString('zh-TW', {
hour: '2-digit',
minute: '2-digit',
second: '2-digit',
hour12: false,
})
} catch {
return iso
}
}
function formatDuration(ms?: number): string | null {
if (ms === undefined || ms === null || ms === 0) return null
if (ms < 1000) return `${ms}ms`
return `${(ms / 1000).toFixed(1)}s`
}
// ----- Status indicator (left-most column) -----
function StatusDot({ status }: { status: StageStatus }) {
if (status === 'running') {
return <Loader2 className="w-4 h-4 text-status-syncing animate-spin" />
}
if (status === 'skipped') {
return <SkipForward className="w-4 h-4 text-nothing-gray-300" />
}
const colorMap: Record<StageStatus, string> = {
success: 'bg-status-healthy shadow-[0_0_6px_rgba(34,197,94,0.4)]',
failed: 'bg-status-critical shadow-[0_0_6px_rgba(255,51,0,0.4)]',
running: 'bg-status-syncing',
skipped: 'bg-nothing-gray-300',
pending: 'bg-nothing-gray-200',
}
return (
<div className={cn('w-3 h-3 rounded-full flex-shrink-0', colorMap[status])} />
)
}
// ----- Main component -----
interface TimelineStageProps {
stage: StageType
status: StageStatus
timestamp: string
duration_ms?: number
data: StageData
/** CSS 動畫延遲(階梯式入場)*/
animationDelay?: number
/** 是否跳過此階段(顯示灰色) */
isSkipped?: boolean
}
export function TimelineStage({
stage,
status,
timestamp,
duration_ms,
data,
animationDelay = 0,
isSkipped = false,
}: TimelineStageProps) {
const t = useTranslations('aiopsTimeline')
const [expanded, setExpanded] = useState(false)
const cfg = STAGE_CONFIG[stage]
const stCfg = STATUS_CONFIG[status]
const Icon = cfg.Icon
const dur = formatDuration(duration_ms)
const canExpand = status !== 'pending' && status !== 'skipped'
return (
<div
className="animate-slide-in-up"
style={{ animationDelay: `${animationDelay}ms`, animationFillMode: 'both' }}
>
{/* Card */}
<div
className={cn(
'bg-white rounded-card border border-nothing-gray-200 shadow-card',
'border-l-4 transition-all duration-200',
cfg.accentClass,
isSkipped && 'opacity-40',
canExpand && 'cursor-pointer hover:shadow-card-hover hover:border-nothing-gray-300',
expanded && 'shadow-card-hover'
)}
onClick={() => canExpand && setExpanded(!expanded)}
role={canExpand ? 'button' : undefined}
tabIndex={canExpand ? 0 : undefined}
aria-expanded={canExpand ? expanded : undefined}
aria-label={canExpand ? t('stage.toggle_details', { stage: t(`stages.${cfg.labelKey}`) }) : undefined}
onKeyDown={(e) => {
if (canExpand && (e.key === 'Enter' || e.key === ' ')) {
e.preventDefault()
setExpanded(!expanded)
}
}}
>
{/* Header Row */}
<div className="flex items-center gap-3 p-3 sm:p-4">
{/* Stage icon */}
<div className={cn('flex-shrink-0 w-8 h-8 rounded-lg flex items-center justify-center', cfg.iconBg)}>
<Icon className={cn('w-4 h-4', cfg.iconColor)} aria-hidden="true" />
</div>
{/* Stage label + status */}
<div className="flex-1 min-w-0">
<div className="flex items-center gap-2 flex-wrap">
<span className="font-heading text-sm font-semibold text-nothing-black">
{t(`stages.${cfg.labelKey}`)}
</span>
<span className={cn(
'inline-flex items-center px-1.5 py-0.5 rounded text-[10px] font-body font-bold uppercase tracking-wider',
stCfg.badge, stCfg.badgeText
)}>
{t(`status.${stCfg.labelKey}`)}
</span>
</div>
{/* Timestamp + duration */}
<div className="flex items-center gap-2 mt-0.5">
<Clock className="w-3 h-3 text-nothing-gray-300" aria-hidden="true" />
<span className="font-body text-[11px] text-nothing-gray-400 tabular-nums">
{formatTs(timestamp)}
</span>
{dur && (
<>
<span className="text-nothing-gray-200">·</span>
<span className="font-body text-[11px] text-nothing-gray-400 tabular-nums">
{dur}
</span>
</>
)}
</div>
</div>
{/* Status dot + chevron */}
<div className="flex items-center gap-2 flex-shrink-0">
<StatusDot status={status} />
{canExpand && (
<div className={cn('transition-transform duration-200', expanded && 'rotate-180')}>
<ChevronDown className="w-4 h-4 text-nothing-gray-400" />
</div>
)}
{!canExpand && <ChevronRight className="w-4 h-4 text-nothing-gray-200" />}
</div>
</div>
{/* Expanded details */}
{expanded && canExpand && (
<div className="px-3 sm:px-4 pb-4 pt-0 border-t border-nothing-gray-100">
<div className="pt-3">
<TimelineStageDetails stage={stage} data={data} />
</div>
</div>
)}
</div>
</div>
)
}

View File

@@ -0,0 +1,359 @@
'use client'
// 2026-04-26 P2.5 by Claude — AIOps Timeline
// ============================================================
// TimelineStageDetails — 展開的詳情區塊
// 每個 stage 有自己的展開格式
// ============================================================
import { useTranslations } from 'next-intl'
import { EvidenceViewer } from './EvidenceViewer'
import { cn } from '@/lib/utils'
import type {
StageType,
StageData,
AlertStageData,
DiagnoseStageData,
DecideStageData,
ExecuteStageData,
VerifyStageData,
LearnStageData,
} from './types'
interface TimelineStageDetailsProps {
stage: StageType
data: StageData
}
// ----- Helper Components -----
function MetaRow({ label, value, mono }: { label: string; value: React.ReactNode; mono?: boolean }) {
return (
<div className="flex items-start gap-2 py-1 border-b border-nothing-gray-100 last:border-0">
<span className="w-32 flex-shrink-0 text-[11px] font-body text-nothing-gray-400 uppercase tracking-wider pt-0.5">
{label}
</span>
<span className={cn('flex-1 text-xs font-body text-nothing-black break-all', mono && 'font-mono')}>
{value}
</span>
</div>
)
}
function LabelBadge({ label, value }: { label: string; value: string }) {
return (
<div className="inline-flex items-center gap-1 px-2 py-0.5 rounded bg-nothing-gray-100 border border-nothing-gray-200">
<span className="text-[10px] font-body text-nothing-gray-400">{label}:</span>
<span className="text-[10px] font-body font-medium text-nothing-black">{value}</span>
</div>
)
}
function ConfidenceBar({ value, threshold }: { value: number; threshold: number }) {
const t = useTranslations('aiopsTimeline')
const pct = Math.min(100, Math.round(value * 100))
const isAbove = value >= threshold
return (
<div className="mt-1">
<div className="h-1.5 bg-nothing-gray-100 rounded-full overflow-hidden">
<div
className={cn(
'h-full rounded-full transition-all',
isAbove ? 'bg-status-healthy' : 'bg-status-warning'
)}
style={{ width: `${pct}%` }}
role="progressbar"
aria-valuenow={pct}
aria-valuemin={0}
aria-valuemax={100}
/>
</div>
<div className="flex items-center justify-between mt-1">
<span className="text-[10px] font-body text-nothing-gray-400">
{pct}%
</span>
<span className="text-[10px] font-body text-nothing-gray-400">
{t('stageDetails.decide.confidenceThreshold', { value: Math.round(threshold * 100) })}
</span>
</div>
</div>
)
}
function TrustBar({ before, after }: { before: number; after: number }) {
const delta = after - before
return (
<div className="flex items-center gap-2">
<span className="text-xs font-body tabular-nums text-nothing-gray-500">{(before * 100).toFixed(0)}%</span>
<div className="flex-1 h-1.5 bg-nothing-gray-100 rounded-full overflow-hidden relative">
<div
className="h-full bg-nothing-gray-300 rounded-full"
style={{ width: `${before * 100}%` }}
/>
<div
className="absolute top-0 h-full bg-status-healthy rounded-full"
style={{ left: `${before * 100}%`, width: `${delta * 100}%` }}
/>
</div>
<span className="text-xs font-body tabular-nums font-medium text-status-healthy">
{(after * 100).toFixed(0)}%
</span>
</div>
)
}
// ----- Stage-specific renderers -----
function AlertDetails({ data }: { data: AlertStageData }) {
const t = useTranslations('aiopsTimeline')
return (
<div className="space-y-0.5">
<MetaRow label={t('stageDetails.alert.name')} value={data.alert_name} />
<MetaRow label={t('stageDetails.alert.rule')} value={<span className="font-mono">{data.rule_matched}</span>} />
{data.raw_value && (
<MetaRow
label={t('stageDetails.alert.value')}
value={
<span className="font-bold text-status-critical">{data.raw_value}
{data.threshold && <span className="font-normal text-nothing-gray-400 ml-1">/ {data.threshold}</span>}
</span>
}
/>
)}
{Object.keys(data.labels).length > 0 && (
<div className="py-1">
<span className="text-[11px] font-body text-nothing-gray-400 uppercase tracking-wider">
{t('stageDetails.alert.labels')}
</span>
<div className="flex flex-wrap gap-1 mt-1.5">
{Object.entries(data.labels).map(([k, v]) => (
<LabelBadge key={k} label={k} value={v} />
))}
</div>
</div>
)}
</div>
)
}
function DiagnoseDetails({ data }: { data: DiagnoseStageData }) {
const t = useTranslations('aiopsTimeline')
return (
<div className="space-y-2">
<MetaRow label={t('stageDetails.diagnose.investigator')} value={data.investigator} />
<div className="py-1">
<span className="text-[11px] font-body text-nothing-gray-400 uppercase tracking-wider">
{t('stageDetails.diagnose.tools_used')}
</span>
<div className="flex flex-wrap gap-1 mt-1.5">
{data.mcp_tools_used.map((tool) => (
<span key={tool} className="px-2 py-0.5 rounded bg-claw-blue/10 border border-claw-blue/20 text-[10px] font-mono text-claw-blue">
{tool}
</span>
))}
</div>
</div>
<MetaRow label={t('stageDetails.diagnose.hypothesis')} value={data.root_cause_hypothesis} />
<div className="pt-1">
<span className="text-[11px] font-body text-nothing-gray-400 uppercase tracking-wider">
{t('stageDetails.diagnose.evidence')}
</span>
<EvidenceViewer dimensions={data.dimensions} />
</div>
</div>
)
}
function DecideDetails({ data }: { data: DecideStageData }) {
const t = useTranslations('aiopsTimeline')
return (
<div className="space-y-0.5">
<MetaRow label={t('stageDetails.decide.engine')} value={data.engine} />
<MetaRow label={t('stageDetails.decide.fusion')} value={data.fusion_method} />
<div className="py-1">
<span className="text-[11px] font-body text-nothing-gray-400 uppercase tracking-wider">
{t('stageDetails.decide.confidence')}
</span>
<ConfidenceBar value={data.confidence} threshold={data.threshold_used} />
</div>
<MetaRow
label={t('stageDetails.decide.auto_execute')}
value={
<span className={cn(
'inline-flex items-center px-1.5 py-0.5 rounded text-[11px] font-body font-bold uppercase',
data.auto_execute
? 'bg-status-healthy/10 text-status-healthy'
: 'bg-status-warning/10 text-status-warning'
)}>
{data.auto_execute ? t('stageDetails.decide.auto_yes') : t('stageDetails.decide.auto_no')}
</span>
}
/>
<MetaRow label={t('stageDetails.decide.playbook')} value={
<span>{data.playbook_name} <span className="text-nothing-gray-400 font-mono">({data.playbook_id})</span></span>
} />
<div className="py-1 border-b border-nothing-gray-100">
<span className="text-[11px] font-body text-nothing-gray-400 uppercase tracking-wider">
{t('stageDetails.decide.decision')}
</span>
<p className="mt-1 text-xs font-mono text-nothing-black bg-nothing-gray-50 border border-nothing-gray-200 rounded px-2 py-1.5 break-all">
{data.decision}
</p>
</div>
<div className="py-1">
<span className="text-[11px] font-body text-nothing-gray-400 uppercase tracking-wider">
{t('stageDetails.decide.reasoning')}
</span>
<p className="mt-1 text-xs font-body text-nothing-gray-700 leading-relaxed">
{data.reasoning}
</p>
</div>
{data.alternate_decisions && data.alternate_decisions.length > 0 && (
<div className="py-1">
<span className="text-[11px] font-body text-nothing-gray-400 uppercase tracking-wider">
{t('stageDetails.decide.alternates')}
</span>
<div className="mt-1.5 space-y-1">
{data.alternate_decisions.map((alt, i) => (
<div key={i} className="flex items-center gap-2 opacity-50">
<div className="w-16 h-1 bg-nothing-gray-200 rounded-full overflow-hidden">
<div className="h-full bg-nothing-gray-400 rounded-full" style={{ width: `${alt.confidence * 100}%` }} />
</div>
<span className="text-[10px] font-mono text-nothing-gray-500 flex-1 truncate">{alt.decision}</span>
<span className="text-[10px] font-body text-nothing-gray-400">{(alt.confidence * 100).toFixed(0)}%</span>
</div>
))}
</div>
</div>
)}
</div>
)
}
function ExecuteDetails({ data }: { data: ExecuteStageData }) {
const t = useTranslations('aiopsTimeline')
return (
<div className="space-y-0.5">
<MetaRow label={t('stageDetails.execute.target')} value={data.target} />
<MetaRow label={t('stageDetails.execute.executor')} value={data.executor} />
<MetaRow label={t('stageDetails.execute.duration')} value={`${(data.duration_ms / 1000).toFixed(1)}s`} />
<div className="py-1">
<span className="text-[11px] font-body text-nothing-gray-400 uppercase tracking-wider">
{t('stageDetails.execute.command')}
</span>
<pre className="mt-1 text-[11px] font-mono text-nothing-black bg-nothing-gray-900 text-nothing-white rounded px-3 py-2 overflow-x-auto whitespace-pre-wrap break-all text-[11px] leading-relaxed" style={{ color: '#e5e5e5' }}>
{data.command}
</pre>
</div>
{data.stdout && (
<div className="py-1">
<span className="text-[11px] font-body text-nothing-gray-400 uppercase tracking-wider">
{t('stageDetails.execute.stdout')}
</span>
<pre className="mt-1 text-[11px] font-mono bg-nothing-gray-900 rounded px-3 py-2 overflow-x-auto whitespace-pre-wrap break-all leading-relaxed" style={{ color: '#86efac' }}>
{data.stdout}
</pre>
</div>
)}
<MetaRow
label={t('stageDetails.execute.exit_code')}
value={
<span className={cn(
'font-mono font-bold',
data.exit_code === 0 ? 'text-status-healthy' : 'text-status-critical'
)}>
{data.exit_code}
</span>
}
/>
</div>
)
}
function VerifyDetails({ data }: { data: VerifyStageData }) {
const t = useTranslations('aiopsTimeline')
const pct = Math.round((data.checks_passed / data.checks_total) * 100)
return (
<div className="space-y-0.5">
<MetaRow label={t('stageDetails.verify.verifier')} value={data.verifier} />
<MetaRow
label={t('stageDetails.verify.outcome')}
value={
<span className={cn(
'inline-flex items-center px-1.5 py-0.5 rounded text-[11px] font-body font-bold uppercase',
data.outcome === 'SUCCESS' ? 'bg-status-healthy/10 text-status-healthy'
: data.outcome === 'PARTIAL' ? 'bg-status-warning/10 text-status-warning'
: 'bg-status-critical/10 text-status-critical'
)}>
{data.outcome}
</span>
}
/>
<div className="py-1">
<span className="text-[11px] font-body text-nothing-gray-400 uppercase tracking-wider">
{t('stageDetails.verify.checks')}
</span>
<div className="flex items-center gap-2 mt-1.5">
<div className="flex-1 h-1.5 bg-nothing-gray-100 rounded-full overflow-hidden">
<div
className={cn('h-full rounded-full', pct === 100 ? 'bg-status-healthy' : 'bg-status-warning')}
style={{ width: `${pct}%` }}
/>
</div>
<span className="text-xs font-body tabular-nums text-nothing-black">
{data.checks_passed}/{data.checks_total}
</span>
</div>
</div>
{data.trust_delta !== 0 && (
<MetaRow
label={t('stageDetails.verify.trust_delta')}
value={
<span className={cn('font-mono font-bold', data.trust_delta > 0 ? 'text-status-healthy' : 'text-status-critical')}>
{data.trust_delta > 0 ? '+' : ''}{(data.trust_delta * 100).toFixed(0)}%
</span>
}
/>
)}
{data.notes && (
<MetaRow label={t('stageDetails.verify.notes')} value={data.notes} />
)}
</div>
)
}
function LearnDetails({ data }: { data: LearnStageData }) {
const t = useTranslations('aiopsTimeline')
return (
<div className="space-y-0.5">
<MetaRow label={t('stageDetails.learn.playbook')} value={<span className="font-mono">{data.playbook_id}</span>} />
<div className="py-1">
<span className="text-[11px] font-body text-nothing-gray-400 uppercase tracking-wider">
{t('stageDetails.learn.trust_update')}
</span>
<div className="mt-2">
<TrustBar before={data.trust_before} after={data.trust_after} />
</div>
</div>
{data.km_entry_id && (
<MetaRow label={t('stageDetails.learn.km_entry')} value={<span className="font-mono">{data.km_entry_id}</span>} />
)}
<MetaRow label={t('stageDetails.learn.summary')} value={data.learning_summary} />
</div>
)
}
// ----- Main export -----
export function TimelineStageDetails({ stage, data }: TimelineStageDetailsProps) {
switch (stage) {
case 'alert': return <AlertDetails data={data as AlertStageData} />
case 'diagnose': return <DiagnoseDetails data={data as DiagnoseStageData} />
case 'decide': return <DecideDetails data={data as DecideStageData} />
case 'execute': return <ExecuteDetails data={data as ExecuteStageData} />
case 'verify': return <VerifyDetails data={data as VerifyStageData} />
case 'learn': return <LearnDetails data={data as LearnStageData} />
default: return null
}
}

View File

@@ -0,0 +1,7 @@
// 2026-04-26 P2.5 by Claude — AIOps Timeline
export { TimelineStage } from './TimelineStage'
export { TimelineStageDetails } from './TimelineStageDetails'
export { TimelineFilter } from './TimelineFilter'
export { EvidenceViewer } from './EvidenceViewer'
export { MOCK_INCIDENTS } from './mock-data'
export type * from './types'

View File

@@ -0,0 +1,357 @@
// 2026-04-26 P2.5 by Claude — AIOps Timeline
// ============================================================
// Mock Data — 3 範例 incident完整 6 階段 + metadata
// NEXT_PUBLIC_AIOPS_TIMELINE_MOCK=true 時使用
// ============================================================
import type { TimelineIncident } from './types'
export const MOCK_INCIDENTS: TimelineIncident[] = [
{
incident_id: 'INC-2026-0425-001',
title: 'API Server CPU 100% — k8s-188',
severity: 'P0',
started_at: '2026-04-25T14:22:03+08:00',
resolved_at: '2026-04-25T14:22:55+08:00',
stages: [
{
stage: 'alert',
status: 'success',
timestamp: '2026-04-25T14:22:03+08:00',
duration_ms: 0,
data: {
alert_name: 'HighCPUUsage',
severity: 'P0',
rule_matched: 'cpu-burst-rule-v3',
labels: {
host: 'k8s-188',
service: 'awoooi-api',
namespace: 'production',
},
annotations: {
summary: 'CPU 使用率超過 98% 持續 5 分鐘',
runbook_url: 'https://wiki.internal/runbooks/high-cpu',
},
raw_value: '100%',
threshold: '95%',
},
},
{
stage: 'diagnose',
status: 'success',
timestamp: '2026-04-25T14:22:04+08:00',
duration_ms: 8240,
data: {
investigator: 'PreDecisionInvestigator v2.1',
mcp_tools_used: [
'kubectl_top_pods',
'kubectl_describe_pod',
'prometheus_query_range',
'loki_logs_tail',
'pg_active_queries',
],
dimensions: [
{ name: 'CPU 使用率', key: 'cpu_usage', value: '100%', status: 'anomaly', detail: 'P99 持續 5m 超限' },
{ name: '記憶體', key: 'memory', value: '68%', status: 'ok', detail: '正常範圍內' },
{ name: 'Pod 狀態', key: 'pod_status', value: 'Running', status: 'ok', detail: '2/2 Ready' },
{ name: '請求速率', key: 'req_rate', value: '4200/s', status: 'anomaly', detail: '正常值 800/s異常 5×' },
{ name: '錯誤率', key: 'error_rate', value: '0.2%', status: 'ok', detail: '< 1% SLO 達標' },
{ name: '最近部署', key: 'last_deploy', value: '4h ago', status: 'ok', detail: 'v2.8.1 穩定' },
{ name: 'DB 查詢', key: 'db_queries', value: 12.4, status: 'anomaly', detail: '平均 12.4ms(基準 2ms' },
{ name: 'GC 壓力', key: 'gc_pressure', value: '45ms/s', status: 'anomaly', detail: 'Full GC 觸發率異常' },
],
summary: '請求速率異常飆升5×正常值觸發 CPU 飽和與 GC 壓力',
root_cause_hypothesis: '流量突增導致 CPU 飽和推測為外部爬蟲或流量攻擊Pod 重啟可短暫緩解',
},
},
{
stage: 'decide',
status: 'success',
timestamp: '2026-04-25T14:22:12+08:00',
duration_ms: 1340,
data: {
engine: 'OpenClaw v3.2',
fusion_method: 'Weighted Confidence Fusion III',
confidence: 0.87,
threshold_used: 0.75,
auto_execute: true,
decision: 'kubectl rollout restart deployment/awoooi-api',
reasoning: '8D 證據確認為暫態流量突增導致的 CPU 飽和;重啟可清除 GC 積壓,同時觸發 HPA 橫向擴展。信心度 0.87 > 自動執行門檻 0.75。',
playbook_id: 'PB-K8S-001',
playbook_name: 'K8s Deployment Restart — CPU High',
alternate_decisions: [
{ decision: 'kubectl scale deployment/awoooi-api --replicas=4', confidence: 0.61 },
{ decision: 'human_approval_required', confidence: 0.13 },
],
},
},
{
stage: 'execute',
status: 'success',
timestamp: '2026-04-25T14:22:13+08:00',
duration_ms: 12400,
data: {
command: 'kubectl rollout restart deployment/awoooi-api -n production',
target: 'deployment/awoooi-api @ k8s-188',
executor: 'AutoExecutor v2.0',
duration_ms: 12400,
stdout: 'deployment.apps/awoooi-api restarted\nWaiting for rollout to finish: 0 of 2 updated replicas are available...\nWaiting for rollout to finish: 1 of 2 updated replicas are available...\ndeployment "awoooi-api" successfully rolled out',
exit_code: 0,
},
},
{
stage: 'verify',
status: 'success',
timestamp: '2026-04-25T14:22:26+08:00',
duration_ms: 29000,
data: {
verifier: 'PostExecutionVerifier v1.4',
outcome: 'SUCCESS',
checks_passed: 5,
checks_total: 5,
trust_delta: 0.05,
notes: 'CPU 回落至 42%,所有 Pod ReadySLO 指標正常',
},
},
{
stage: 'learn',
status: 'success',
timestamp: '2026-04-25T14:22:55+08:00',
duration_ms: 210,
data: {
playbook_id: 'PB-K8S-001',
trust_before: 0.50,
trust_after: 0.55,
km_entry_id: 'KM-20260425-0312',
learning_summary: 'Playbook PB-K8S-001 信任度 +0.050.50 → 0.55)。成功處置 CPU 突增事件,記錄至知識庫。',
},
},
],
},
{
incident_id: 'INC-2026-0424-007',
title: 'PostgreSQL 備份失敗 — host-110',
severity: 'P1',
started_at: '2026-04-24T03:15:00+08:00',
resolved_at: '2026-04-24T03:21:44+08:00',
stages: [
{
stage: 'alert',
status: 'success',
timestamp: '2026-04-24T03:15:00+08:00',
duration_ms: 0,
data: {
alert_name: 'HostBackupFailed',
severity: 'P1',
rule_matched: 'backup-age-rule-v2',
labels: { host: 'host-110', job: 'pg-backup-cron' },
annotations: { summary: '備份任務超過 25 小時未成功' },
raw_value: '26h ago',
threshold: '25h',
},
},
{
stage: 'diagnose',
status: 'success',
timestamp: '2026-04-24T03:15:01+08:00',
duration_ms: 6800,
data: {
investigator: 'PreDecisionInvestigator v2.1',
mcp_tools_used: [
'ssh_exec',
'pg_backup_status',
'disk_usage_check',
'cron_log_tail',
],
dimensions: [
{ name: '備份年齡', key: 'backup_age', value: '26h', status: 'anomaly', detail: '超過 25h 門檻' },
{ name: '磁碟空間', key: 'disk_free', value: '2.1GB', status: 'anomaly', detail: '備份目錄空間不足' },
{ name: 'PG 狀態', key: 'pg_status', value: 'running', status: 'ok', detail: 'PostgreSQL 正常運行' },
{ name: 'Cron 日誌', key: 'cron_log', value: 'FAILED', status: 'anomaly', detail: 'No space left on device' },
{ name: '上次備份', key: 'last_backup', value: null, status: 'unknown', detail: '無法取得' },
{ name: '網路', key: 'network', value: 'ok', status: 'ok', detail: 'Remote host 可達' },
{ name: '備份腳本', key: 'script_status', value: 'exist', status: 'ok', detail: '/opt/backup/pg_backup.sh 存在' },
{ name: '排程狀態', key: 'cron_enabled', value: 'enabled', status: 'ok', detail: 'Cron job 已啟用' },
],
summary: '備份目錄磁碟空間不足(僅剩 2.1GB),導致備份任務失敗',
root_cause_hypothesis: '磁碟空間耗盡,需清理舊備份後重新執行',
},
},
{
stage: 'decide',
status: 'success',
timestamp: '2026-04-24T03:15:08+08:00',
duration_ms: 890,
data: {
engine: 'OpenClaw v3.2',
fusion_method: 'Weighted Confidence Fusion III',
confidence: 0.91,
threshold_used: 0.75,
auto_execute: true,
decision: 'cleanup_old_backups && trigger_pg_backup',
reasoning: '磁碟空間不足是明確根因,清理 7 天前備份後重新執行可解決。信心度 0.91 高於門檻。',
playbook_id: 'PB-BACKUP-001',
playbook_name: 'Backup Disk Cleanup & Retry',
alternate_decisions: [
{ decision: 'human_approval_required', confidence: 0.09 },
],
},
},
{
stage: 'execute',
status: 'success',
timestamp: '2026-04-24T03:15:09+08:00',
duration_ms: 394000,
data: {
command: 'find /backup -name "*.sql.gz" -mtime +7 -delete && /opt/backup/pg_backup.sh',
target: 'host-110 via SSH',
executor: 'AutoExecutor v2.0',
duration_ms: 394000,
stdout: 'Cleaned 8 files (12.3GB freed)\nStarting PostgreSQL backup...\nBackup completed: /backup/pg_2026-04-24_031509.sql.gz (3.2GB)',
exit_code: 0,
},
},
{
stage: 'verify',
status: 'success',
timestamp: '2026-04-24T03:21:32+08:00',
duration_ms: 12000,
data: {
verifier: 'PostExecutionVerifier v1.4',
outcome: 'SUCCESS',
checks_passed: 4,
checks_total: 4,
trust_delta: 0.05,
notes: '備份檔案存在且大小合理磁碟空間恢復正常14.4GB 可用)',
},
},
{
stage: 'learn',
status: 'success',
timestamp: '2026-04-24T03:21:44+08:00',
duration_ms: 180,
data: {
playbook_id: 'PB-BACKUP-001',
trust_before: 0.65,
trust_after: 0.70,
km_entry_id: 'KM-20260424-0089',
learning_summary: 'Playbook PB-BACKUP-001 信任度 +0.050.65 → 0.70)。建議增加磁碟空間預警規則。',
},
},
],
},
{
incident_id: 'INC-2026-0423-015',
title: 'Cadvisor OOM — monitoring namespace',
severity: 'P2',
started_at: '2026-04-23T09:41:22+08:00',
stages: [
{
stage: 'alert',
status: 'success',
timestamp: '2026-04-23T09:41:22+08:00',
duration_ms: 0,
data: {
alert_name: 'ContainerOOMKilled',
severity: 'P2',
rule_matched: 'oom-kill-detection-v1',
labels: {
container: 'cadvisor',
namespace: 'monitoring',
node: 'k8s-188',
},
annotations: { summary: 'cadvisor 被 OOM Killer 終止' },
raw_value: 'OOMKilled',
},
},
{
stage: 'diagnose',
status: 'success',
timestamp: '2026-04-23T09:41:23+08:00',
duration_ms: 5400,
data: {
investigator: 'PreDecisionInvestigator v2.1',
mcp_tools_used: [
'kubectl_describe_pod',
'kubectl_top_pods',
'prometheus_memory_usage',
],
dimensions: [
{ name: 'OOM 事件', key: 'oom_event', value: 'OOMKilled', status: 'anomaly', detail: 'cadvisor 觸發 OOM' },
{ name: 'Memory limit', key: 'mem_limit', value: '256Mi', status: 'anomaly', detail: '限制過低' },
{ name: 'Memory 實際', key: 'mem_actual', value: '260Mi+', status: 'anomaly', detail: '超過 limit' },
{ name: 'CPU', key: 'cpu', value: '288%', status: 'anomaly', detail: '已持續異常 13 天(監控盲區)' },
{ name: 'Pod 重啟', key: 'restart_count', value: 47, status: 'anomaly', detail: '47 次重啟' },
{ name: '影響範圍', key: 'blast_radius', value: '監控層', status: 'anomaly', detail: '指標採集中斷' },
{ name: '其他 Pod', key: 'other_pods', value: '正常', status: 'ok', detail: '其餘 monitoring pod 正常' },
{ name: '節點資源', key: 'node_resources', value: '充裕', status: 'ok', detail: '節點整體資源正常' },
],
summary: 'cadvisor memory limit 設定過低256Mi實際需求超過限制導致 OOM',
root_cause_hypothesis: '提高 cadvisor memory limit 至 512Mi 並重啟',
},
},
{
stage: 'decide',
status: 'success',
timestamp: '2026-04-23T09:41:29+08:00',
duration_ms: 1200,
data: {
engine: 'OpenClaw v3.2',
fusion_method: 'Weighted Confidence Fusion III',
confidence: 0.78,
threshold_used: 0.75,
auto_execute: true,
decision: 'kubectl patch daemonset cadvisor -p memory_limit=512Mi',
reasoning: '根因明確memory limit 過低),提升 limit 後重啟即可。影響範圍僅監控層,無業務風險。',
playbook_id: 'PB-K8S-OOM-001',
playbook_name: 'K8s OOM — Increase Memory Limit',
alternate_decisions: [
{ decision: 'kubectl delete pod cadvisor (restart only)', confidence: 0.20 },
{ decision: 'human_approval_required', confidence: 0.02 },
],
},
},
{
stage: 'execute',
status: 'success',
timestamp: '2026-04-23T09:41:30+08:00',
duration_ms: 8300,
data: {
command: 'kubectl patch daemonset cadvisor -n monitoring --type merge -p \'{"spec":{"template":{"spec":{"containers":[{"name":"cadvisor","resources":{"limits":{"memory":"512Mi"}}}]}}}}\'',
target: 'daemonset/cadvisor @ monitoring',
executor: 'AutoExecutor v2.0',
duration_ms: 8300,
stdout: 'daemonset.apps/cadvisor patched\ncadvisor-xk2p9 restarted',
exit_code: 0,
},
},
{
stage: 'verify',
status: 'success',
timestamp: '2026-04-23T09:41:39+08:00',
duration_ms: 45000,
data: {
verifier: 'PostExecutionVerifier v1.4',
outcome: 'SUCCESS',
checks_passed: 3,
checks_total: 4,
trust_delta: 0.03,
notes: 'cadvisor RunningOOM 事件消除。CPU 仍 220%(長期問題,已記錄待 P2.6 處理)',
},
},
{
stage: 'learn',
status: 'success',
timestamp: '2026-04-23T09:42:24+08:00',
duration_ms: 160,
data: {
playbook_id: 'PB-K8S-OOM-001',
trust_before: 0.40,
trust_after: 0.43,
km_entry_id: 'KM-20260423-0156',
learning_summary: 'Playbook PB-K8S-OOM-001 信任度 +0.030.40 → 0.43。cadvisor CPU 問題已記錄為待處理項目。',
},
},
],
},
]

View File

@@ -0,0 +1,118 @@
// 2026-04-26 P2.5 by Claude — AIOps Timeline
// ============================================================
// AIOps Timeline 型別定義
// 告警→決策→執行→驗證鏈路資料結構
// ============================================================
export type StageStatus = 'success' | 'running' | 'failed' | 'skipped' | 'pending'
export type StageType =
| 'alert'
| 'diagnose'
| 'decide'
| 'execute'
| 'verify'
| 'learn'
// ----- Alert Stage -----
export interface AlertStageData {
alert_name: string
severity: 'P0' | 'P1' | 'P2' | 'P3'
rule_matched: string
labels: Record<string, string>
annotations: Record<string, string>
raw_value?: string
threshold?: string
}
// ----- Diagnose Stage -----
export interface EvidenceDimension {
name: string
key: string
value: string | number | null
status: 'ok' | 'anomaly' | 'unknown'
detail?: string
}
export interface DiagnoseStageData {
investigator: string
mcp_tools_used: string[]
dimensions: EvidenceDimension[]
summary: string
root_cause_hypothesis: string
}
// ----- Decide Stage -----
export interface DecideStageData {
engine: string
fusion_method: string
confidence: number
threshold_used: number
auto_execute: boolean
decision: string
reasoning: string
playbook_id: string
playbook_name: string
alternate_decisions?: Array<{ decision: string; confidence: number }>
}
// ----- Execute Stage -----
export interface ExecuteStageData {
command: string
target: string
executor: string
duration_ms: number
stdout?: string
stderr?: string
exit_code: number
}
// ----- Verify Stage -----
export interface VerifyStageData {
verifier: string
outcome: 'SUCCESS' | 'PARTIAL' | 'FAILED' | 'TIMEOUT'
checks_passed: number
checks_total: number
trust_delta: number
notes?: string
}
// ----- Learn Stage -----
export interface LearnStageData {
playbook_id: string
trust_before: number
trust_after: number
km_entry_id?: string
learning_summary: string
}
export type StageData =
| AlertStageData
| DiagnoseStageData
| DecideStageData
| ExecuteStageData
| VerifyStageData
| LearnStageData
export interface TimelineStageEntry {
stage: StageType
status: StageStatus
timestamp: string // ISO 8601
duration_ms?: number
data: StageData
}
export interface TimelineIncident {
incident_id: string
title: string
severity: 'P0' | 'P1' | 'P2' | 'P3'
started_at: string
resolved_at?: string
stages: TimelineStageEntry[]
}
export interface TimelineFilterState {
incident_id: string
time_range: '1h' | '6h' | '24h' | '7d' | 'custom'
status_filter: 'all' | 'success' | 'failed' | 'running'
}