Files
Neo-ZQYY/apps/admin-web/src/pages/AIDashboard.tsx
Neo c43375734a feat(admin-web,backend): F1-5b Wave B UI-3 + UI-5 admin-web sandbox 透出补强 (W1)
UI-3 AIDashboard sandbox 提示 + today_calls 分组:
- 后端 schemas/admin_ai.py DashboardResponse 加 today_live_calls / today_sandbox_calls 字段(默认 0,向后兼容)
- 后端 services/ai/admin_service.py _get_range_stats SELECT 加 2 个 FILTER COUNT 表达式
- 前端 api/adminAI.ts DashboardResponse 类型补 2 字段
- 前端 pages/AIDashboard.tsx
  - 顶部加 sandbox Alert 提示条,选中 site sandbox 模式下显示业务日 + 实例 ID
  - today_calls 卡片下方加分组 Tag(实时 X / 沙箱 Y),feature flag 控制
  - import fetchRuntimeContext + useEffect 拉 RuntimeContext
- apps/admin-web/.env.example 新建,加 VITE_AI_RUNTIME_GROUPING=false 默认值说明

UI-5 AITriggerJobs runtime 列:
- 后端 schemas/admin_ai.py TriggerJobItem 加 runtime_mode / sandbox_instance_id 可选字段
- 后端 admin_service.py list_trigger_jobs / get_trigger_job 各加 SELECT 列
- 前端 adminAI.ts TriggerJobItem 类型补 2 字段
- 前端 pages/AITriggerJobs.tsx 列表 columns 加运行模式 + 沙箱实例(同 UI-1 模式),详情 Modal 加 2 项(同 UI-2 模式)

双口径验证(Playwright + DB 直查):
- UI-3 4a live: 选中默认门店,无 Alert,today_card 仅显示总数(flag off)
- UI-3 4b sandbox=4-20: Alert 显示"沙箱 + 业务日 + sbx_…",today_calls=93(sandbox 当日)
- UI-5 4a/4b: SQL INSERT 注入 walkthrough 测试行(id=9 live, id=10 sandbox),列表正确渲染 Tag + 短哈希

trend_7d 双线 / app_distribution 堆叠分布等更深入分组改造延后到 Wave C(§8.3 风险:破坏图表)。

审计:
- docs/audit/changes/2026-05-05__wave1_f1_5b_ui3_aidashboard_sandbox.md
- docs/audit/changes/2026-05-05__wave1_f1_5b_ui5_aitriggerjobs_runtime.md

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-05 19:16:47 +08:00

364 lines
13 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* AI 运行总览 Dashboard 页面。
*
* - 顶部:门店筛选 + 刷新
* - 第一行4 个统计卡片今日调用、成功率、Token 消耗、平均延迟)
* - 第二行7 天趋势表格 + App 调用占比表格
* - 第三行Token 预算进度条 + App 健康状态
* - 第四行:告警列表
*/
import React, { useEffect, useRef, useState, useCallback } from "react";
import {
Card, Row, Col, Statistic, Table, Tag, Badge, Progress,
Select, Button, message, Typography, Space, DatePicker, Alert,
} from "antd";
import { ReloadOutlined, WifiOutlined } from "@ant-design/icons";
import type { Dayjs } from "dayjs";
// F1-5b UI-3: sandbox 提示条复用 UI-4 同款 RuntimeContext fetch
import { fetchRuntimeContext, type RuntimeContext } from "../api/runtimeContext";
// F1-5b UI-3: feature flag — today_calls 分组数字是否展示。
// 默认 false(防止图表回归);开启时 today_calls 卡片下方显示 "实时 X / 沙箱 Y"。
const RUNTIME_GROUPING_ENABLED =
String(import.meta.env.VITE_AI_RUNTIME_GROUPING ?? "").toLowerCase() === "true";
const { RangePicker } = DatePicker;
const RANGE_OPTIONS = [
{ label: "今日", value: 1 },
{ label: "近 3 天", value: 3 },
{ label: "近 7 天", value: 7 },
{ label: "近 10 天", value: 10 },
{ label: "指定日期", value: 0 }, // 0 = 启用 RangePicker
];
const RANGE_LABEL: Record<number, string> = {
1: "今日", 3: "近 3 天", 7: "近 7 天", 10: "近 10 天",
};
import type { ColumnsType } from "antd/es/table";
import {
getDashboard,
type DashboardResponse, type DailyTrend, type AppDistItem,
type AlertItem, type AppHealthItem,
} from "../api/adminAI";
const { Title } = Typography;
const ALERT_STATUS_COLOR: Record<string, string> = {
failed: "red", timeout: "orange", circuit_open: "volcano",
};
const ALERT_MGMT_COLOR: Record<string, string> = {
pending: "warning", acknowledged: "success", ignored: "default",
};
const HEALTH_STATUS: Record<string, "success" | "error" | "warning" | "default"> = {
success: "success", failed: "error", timeout: "warning", circuit_open: "error",
};
function fmtTime(raw: string | null): string {
if (!raw) return "—";
const d = new Date(raw);
return Number.isNaN(d.getTime()) ? raw : d.toLocaleString("zh-CN");
}
// ---- 表格列定义 ----
const trendColumns: ColumnsType<DailyTrend> = [
{ title: "日期", dataIndex: "date", key: "date", width: 120 },
{ title: "调用量", dataIndex: "calls", key: "calls", align: "right" },
{
title: "成功率", dataIndex: "success_rate", key: "success_rate", align: "right",
render: (v: number) => `${(v * 100).toFixed(1)}%`,
},
];
const distColumns: ColumnsType<AppDistItem> = [
{ title: "App 类型", dataIndex: "app_type", key: "app_type" },
{ title: "调用次数", dataIndex: "count", key: "count", align: "right" },
{
title: "占比", dataIndex: "percentage", key: "percentage", align: "right",
render: (v: number) => `${(v * 100).toFixed(1)}%`,
},
];
const alertColumns: ColumnsType<AlertItem> = [
{ title: "ID", dataIndex: "id", key: "id", width: 80 },
{ title: "App", dataIndex: "app_type", key: "app_type", width: 160 },
{
title: "状态", dataIndex: "status", key: "status", width: 110,
render: (v: string) => <Tag color={ALERT_STATUS_COLOR[v] ?? "default"}>{v}</Tag>,
},
{
title: "告警状态", dataIndex: "alert_status", key: "alert_status", width: 110,
render: (v: string | null) => v ? <Tag color={ALERT_MGMT_COLOR[v] ?? "default"}>{v}</Tag> : "—",
},
{
title: "错误信息", dataIndex: "error_message", key: "error_message", ellipsis: true,
render: (v: string | null) => v ?? "—",
},
{ title: "时间", dataIndex: "created_at", key: "created_at", width: 170, render: fmtTime },
];
// ---- 页面组件 ----
const AIDashboard: React.FC = () => {
const [data, setData] = useState<DashboardResponse | null>(null);
const [loading, setLoading] = useState(false);
const [siteId, setSiteId] = useState<number | undefined>(undefined);
const [rangeDays, setRangeDays] = useState<number>(1); // 0=自定义日期 / 1/3/7/10
const [customRange, setCustomRange] = useState<[Dayjs, Dayjs] | null>(null);
const [wsStatus, setWsStatus] = useState<"connecting" | "connected" | "disconnected">("disconnected");
const [realtimeAlerts, setRealtimeAlerts] = useState<AlertItem[]>([]);
const wsRef = useRef<WebSocket | null>(null);
// F1-5b UI-3: 当前选中 site 的 RuntimeContext,用于顶部 sandbox 提示条
const [runtimeCtx, setRuntimeCtx] = useState<RuntimeContext | null>(null);
const load = useCallback(async () => {
setLoading(true);
try {
const query: { site_id?: number; range_days?: number; date_from?: string; date_to?: string } = {};
if (siteId != null) query.site_id = siteId;
if (rangeDays === 0 && customRange) {
query.date_from = customRange[0].format("YYYY-MM-DD");
query.date_to = customRange[1].format("YYYY-MM-DD");
} else if (rangeDays > 0) {
query.range_days = rangeDays;
}
const res = await getDashboard(query);
setData(res);
} catch {
message.error("加载 Dashboard 失败");
} finally {
setLoading(false);
}
}, [siteId, rangeDays, customRange]);
useEffect(() => { load(); }, [load]);
// F1-5b UI-3: 拉取当前 site 的 RuntimeContext。siteId 未选时不显示提示条。
useEffect(() => {
if (siteId == null) {
setRuntimeCtx(null);
return;
}
let cancelled = false;
fetchRuntimeContext(siteId)
.then((ctx) => { if (!cancelled) setRuntimeCtx(ctx); })
.catch(() => { if (!cancelled) setRuntimeCtx(null); });
return () => { cancelled = true; };
}, [siteId]);
const statLabel = rangeDays === 0
? (customRange ? `${customRange[0].format("MM-DD")} ~ ${customRange[1].format("MM-DD")}` : "指定日期")
: (RANGE_LABEL[rangeDays] || "今日");
// WebSocket 实时告警订阅
useEffect(() => {
const wsKey = siteId ?? -1;
const proto = window.location.protocol === "https:" ? "wss" : "ws";
const url = `${proto}://${window.location.host}/ws/ai-alerts/${wsKey}`;
setWsStatus("connecting");
const ws = new WebSocket(url);
wsRef.current = ws;
ws.onopen = () => setWsStatus("connected");
ws.onclose = () => setWsStatus("disconnected");
ws.onerror = () => setWsStatus("disconnected");
ws.onmessage = (evt) => {
try {
const msg = JSON.parse(evt.data as string) as {
type: string;
payload: AlertItem;
};
if (msg.type === "alert_created" && msg.payload) {
setRealtimeAlerts((prev) => [msg.payload, ...prev].slice(0, 20));
message.warning(`[实时] ${msg.payload.app_type} ${msg.payload.status}`);
}
} catch {
// 忽略非 JSON 消息
}
};
return () => {
ws.close();
wsRef.current = null;
setWsStatus("disconnected");
};
}, [siteId]);
return (
<div>
{/* 顶部:门店筛选 + 刷新 */}
<Row justify="space-between" align="middle" style={{ marginBottom: 16 }}>
<Space wrap>
<Title level={4} style={{ margin: 0 }}>AI </Title>
<Select
allowClear placeholder="门店筛选" style={{ width: 180 }}
value={siteId} onChange={(v) => setSiteId(v)}
options={[{ label: "默认门店", value: 2790685415443269 }]}
/>
<Select
value={rangeDays} onChange={setRangeDays} style={{ width: 140 }}
options={RANGE_OPTIONS}
/>
{rangeDays === 0 && (
<RangePicker
value={customRange}
onChange={(v) => setCustomRange(v as [Dayjs, Dayjs] | null)}
/>
)}
</Space>
<Space>
<Badge
status={wsStatus === "connected" ? "success" : wsStatus === "connecting" ? "processing" : "default"}
text={<span style={{ fontSize: 12, color: "#888" }}><WifiOutlined /> {wsStatus === "connected" ? "已连接" : wsStatus === "connecting" ? "连接中" : "断开"}</span>}
/>
<Button icon={<ReloadOutlined />} onClick={load} loading={loading}></Button>
</Space>
</Row>
{/* F1-5b UI-3: sandbox 提示条 — 仅当选中 site 处于 sandbox 模式时显示 */}
{runtimeCtx?.is_sandbox && (
<Alert
type="warning"
showIcon
style={{ marginBottom: 16 }}
message={
<Space size={8}>
<Tag color="orange" style={{ margin: 0 }}></Tag>
<span>,</span>
<Tag color="default" style={{ fontFamily: "monospace" }}>{runtimeCtx.business_date}</Tag>
{runtimeCtx.sandbox_instance_id && (
<span style={{ fontSize: 12, color: "#888", fontFamily: "monospace" }}>
{runtimeCtx.sandbox_instance_id.slice(0, 12)}
</span>
)}
</Space>
}
/>
)}
{/* 第一行4 个统计卡片 */}
<Row gutter={16} style={{ marginBottom: 16 }}>
<Col span={6}>
<Card>
<Statistic title={`${statLabel}调用次数`} value={data?.today_calls ?? 0} />
{/* F1-5b UI-3: feature flag 控制 — today_calls 按 runtime 分组数字 */}
{RUNTIME_GROUPING_ENABLED && data && (
<div style={{ marginTop: 4, fontSize: 12, color: "#888" }}>
<Tag color="blue" style={{ marginRight: 4 }}> {data.today_live_calls}</Tag>
<Tag color="orange" style={{ margin: 0 }}> {data.today_sandbox_calls}</Tag>
</div>
)}
</Card>
</Col>
<Col span={6}>
<Card>
<Statistic
title={`${statLabel}成功率`} suffix="%"
value={data ? (data.today_success_rate * 100).toFixed(1) : "0.0"}
/>
</Card>
</Col>
<Col span={6}>
<Card><Statistic title={`${statLabel} Token 消耗`} value={data?.today_tokens ?? 0} /></Card>
</Col>
<Col span={6}>
<Card>
<Statistic
title="平均延迟" suffix="ms"
value={data ? data.today_avg_latency_ms.toFixed(0) : "0"}
/>
</Card>
</Col>
</Row>
{/* 第二行7 天趋势 + App 调用占比 */}
<Row gutter={16} style={{ marginBottom: 16 }}>
<Col span={12}>
<Card title="近 7 天趋势" size="small">
<Table<DailyTrend>
columns={trendColumns}
dataSource={data?.trend_7d ?? []}
rowKey="date" size="small" pagination={false}
loading={loading}
/>
</Card>
</Col>
<Col span={12}>
<Card title="App 调用占比" size="small">
<Table<AppDistItem>
columns={distColumns}
dataSource={data?.app_distribution ?? []}
rowKey="app_type" size="small" pagination={false}
loading={loading}
/>
</Card>
</Col>
</Row>
{/* 第三行Token 预算 + App 健康状态 */}
<Row gutter={16} style={{ marginBottom: 16 }}>
<Col span={12}>
<Card title="Token 预算" size="small">
<div style={{ marginBottom: 12 }}>
<span>{data?.budget.daily_used ?? 0} / {data?.budget.daily_limit ?? 0}</span>
<Progress
percent={data ? +(data.budget.daily_pct * 100).toFixed(1) : 0}
status={data && data.budget.daily_pct > 0.9 ? "exception" : "active"}
/>
</div>
<div>
<span>{data?.budget.monthly_used ?? 0} / {data?.budget.monthly_limit ?? 0}</span>
<Progress
percent={data ? +(data.budget.monthly_pct * 100).toFixed(1) : 0}
status={data && data.budget.monthly_pct > 0.9 ? "exception" : "active"}
/>
</div>
</Card>
</Col>
<Col span={12}>
<Card title="App 健康状态" size="small">
{(data?.app_health ?? []).map((item: AppHealthItem) => (
<div key={item.app_type} style={{ display: "flex", justifyContent: "space-between", padding: "4px 0" }}>
<span>{item.app_type}</span>
<Space>
<Badge status={HEALTH_STATUS[item.last_status ?? ""] ?? "default"} text={item.last_status ?? "无记录"} />
<span style={{ fontSize: 12, color: "#999" }}>{fmtTime(item.last_call_at)}</span>
</Space>
</div>
))}
{(data?.app_health ?? []).length === 0 && <span style={{ color: "#999" }}></span>}
</Card>
</Col>
</Row>
{/* 第四行:告警列表(实时 + 历史合并) */}
<Card
title="告警列表"
size="small"
extra={realtimeAlerts.length > 0 && (
<Tag color="orange">{realtimeAlerts.length} </Tag>
)}
>
<Table<AlertItem>
columns={alertColumns}
dataSource={[
...realtimeAlerts,
...(data?.recent_alerts ?? []).filter(
(a) => !realtimeAlerts.some((r) => r.id === a.id)
),
]}
rowKey="id" size="small" pagination={{ pageSize: 10 }}
loading={loading}
/>
</Card>
</div>
);
};
export default AIDashboard;