From 7a10645012f4aa38f77e320148be39621182026f Mon Sep 17 00:00:00 2001 From: ji ruo <79234113+RuoJi6@users.noreply.github.com> Date: Thu, 3 Dec 2026 16:00:17 +0800 Subject: [PATCH] feat(dashboard): add vulnerability, container, and lifecycle trend chart - Add full-width multi-tab area/line trend chart above Activity & Findings on /dashboard. - Support 7d/14d/30d local day buckets across findings, container creations, and task/finding lifecycle. - Add bilingual i18n keys, mock /sandbox/status route, and migrated-page i18n test coverage. --- .../_components/environment-lifecycle-row.tsx | 478 ++++++++++++++++++ web/src/app/(main)/dashboard/page.tsx | 61 ++- web/src/i18n/i18n.test.cjs | 1 + web/src/i18n/overview-messages.ts | 39 ++ web/src/lib/mock/handler.ts | 37 ++ 5 files changed, 615 insertions(+), 1 deletion(-) create mode 100644 web/src/app/(main)/dashboard/_components/environment-lifecycle-row.tsx diff --git a/web/src/app/(main)/dashboard/_components/environment-lifecycle-row.tsx b/web/src/app/(main)/dashboard/_components/environment-lifecycle-row.tsx new file mode 100644 index 0000000..6a24ac1 --- /dev/null +++ b/web/src/app/(main)/dashboard/_components/environment-lifecycle-row.tsx @@ -0,0 +1,478 @@ +"use client"; + +import * as React from "react"; + +import Link from "next/link"; + +import { ArrowUpRightIcon } from "lucide-react"; +import { Area, AreaChart, CartesianGrid, Tooltip as RechartsTooltip, XAxis, YAxis } from "recharts"; + +import { Badge } from "@/components/ui/badge"; +import { Card } from "@/components/ui/card"; +import { type ChartConfig, ChartContainer } from "@/components/ui/chart"; +import { useLiveTranslation } from "@/i18n/use-live-translation"; +import type { ActiveFindingRetest, Finding, FindingStatus, SandboxGlobalStatus, Task } from "@/lib/types"; +import { cn } from "@/lib/utils"; + +type TrendTab = "findings" | "containers" | "lifecycle"; +type WindowDays = 7 | 14 | 30; + +interface DayBucket { + dayKey: string; + label: string; + findingsTotal: number; + findingsHighCrit: number; + findingsMedLow: number; + findingsClosed: number; + containersCreated: number; + containersRunning: number; + containersTask: number; + containersSession: number; + tasksCreated: number; + tasksCompleted: number; +} + +const CLOSED_FINDING_STATUS: Partial> = { + resolved: true, + fixed: true, + false_positive: true, + ignored: true, + duplicate: true, + risk_accepted: true, +}; + +const WINDOW_OPTIONS: readonly WindowDays[] = [7, 14, 30]; + +function toLocalDayKey(date: Date): string { + const y = date.getFullYear(); + const m = String(date.getMonth() + 1).padStart(2, "0"); + const d = String(date.getDate()).padStart(2, "0"); + return `${y}-${m}-${d}`; +} + +function parseTimestamp(ts?: string | number): Date | null { + if (!ts) return null; + if (typeof ts === "number") { + if (ts <= 0) return null; + const d = new Date(ts * 1000); + return Number.isNaN(d.getTime()) ? null : d; + } + const ms = Date.parse(ts); + if (Number.isNaN(ms)) return null; + return new Date(ms); +} + +export function EnvironmentLifecycleRow({ + sandboxStatus, + findings, + tasks, + activeRetests, +}: { + sandboxStatus: SandboxGlobalStatus | null; + findings: Finding[]; + tasks: Task[]; + activeRetests: ActiveFindingRetest[]; +}) { + const { t: translate } = useLiveTranslation(); + const [tab, setTab] = React.useState("findings"); + const [days, setDays] = React.useState(7); + + const { buckets, summary } = React.useMemo(() => { + const today = new Date(); + today.setHours(0, 0, 0, 0); + + const list: DayBucket[] = []; + const byKey = new Map(); + for (let i = days - 1; i >= 0; i--) { + const d = new Date(today); + d.setDate(today.getDate() - i); + const dayKey = toLocalDayKey(d); + const bucket: DayBucket = { + dayKey, + label: dayKey.slice(5).replace("-", "/"), + findingsTotal: 0, + findingsHighCrit: 0, + findingsMedLow: 0, + findingsClosed: 0, + containersCreated: 0, + containersRunning: 0, + containersTask: 0, + containersSession: 0, + tasksCreated: 0, + tasksCompleted: 0, + }; + list.push(bucket); + byKey.set(dayKey, bucket); + } + + let windowFindings = 0; + let windowHighCrit = 0; + let windowClosedFindings = 0; + let totalClosedFindings = 0; + + for (const f of findings) { + const isClosed = Boolean(CLOSED_FINDING_STATUS[f.status]); + if (isClosed) totalClosedFindings++; + const dt = parseTimestamp(f.ts); + if (!dt) continue; + const bucket = byKey.get(toLocalDayKey(dt)); + if (!bucket) continue; + bucket.findingsTotal++; + windowFindings++; + if (f.severity === "critical" || f.severity === "high") { + bucket.findingsHighCrit++; + windowHighCrit++; + } else { + bucket.findingsMedLow++; + } + if (isClosed) { + bucket.findingsClosed++; + windowClosedFindings++; + } + } + + const containers = Array.isArray(sandboxStatus?.containers) ? sandboxStatus.containers : []; + let windowContainersCreated = 0; + let currentRunningContainers = 0; + let currentStoppedContainers = 0; + + for (const c of containers) { + if (c.state === "running") currentRunningContainers++; + else currentStoppedContainers++; + const dt = parseTimestamp(c.created_at); + if (!dt) continue; + const bucket = byKey.get(toLocalDayKey(dt)); + if (!bucket) continue; + bucket.containersCreated++; + windowContainersCreated++; + if (c.state === "running") bucket.containersRunning++; + if (c.scope === "task") bucket.containersTask++; + else if (c.scope === "session") bucket.containersSession++; + } + + let windowTasksCreated = 0; + let windowTasksCompleted = 0; + + for (const t of tasks) { + const createdDt = parseTimestamp(t.created_unix ?? t.created_at); + if (createdDt) { + const b = byKey.get(toLocalDayKey(createdDt)); + if (b) { + b.tasksCreated++; + windowTasksCreated++; + } + } + const completedDt = parseTimestamp(t.completed_unix && t.completed_unix > 0 ? t.completed_unix : t.completed_at); + if (completedDt) { + const b = byKey.get(toLocalDayKey(completedDt)); + if (b) { + b.tasksCompleted++; + windowTasksCompleted++; + } + } + } + + const closureRate = findings.length > 0 ? Math.round((totalClosedFindings / findings.length) * 100) : 0; + + return { + buckets: list, + summary: { + windowFindings, + windowHighCrit, + windowClosedFindings, + windowContainersCreated, + currentRunningContainers, + currentStoppedContainers, + windowTasksCreated, + windowTasksCompleted, + closureRate, + }, + }; + }, [days, findings, sandboxStatus, tasks]); + + const seriesByTab = { + findings: { + primaryKey: "findingsTotal" as const, + primaryLabel: translate("overview.trendSeriesFindings"), + secondaryKey: "findingsHighCrit" as const, + secondaryLabel: translate("overview.trendSeriesHighCrit"), + secondaryColor: "#f43f5e", + }, + containers: { + primaryKey: "containersCreated" as const, + primaryLabel: translate("overview.trendSeriesContainersCreated"), + secondaryKey: "containersRunning" as const, + secondaryLabel: translate("overview.trendSeriesContainersRunning"), + secondaryColor: "#10b981", + }, + lifecycle: { + primaryKey: "tasksCreated" as const, + primaryLabel: translate("overview.trendSeriesTasksCreated"), + secondaryKey: "tasksCompleted" as const, + secondaryLabel: translate("overview.trendSeriesTasksCompleted"), + secondaryColor: "#10b981", + }, + }; + const activeSeries = seriesByTab[tab]; + + const chartConfig: ChartConfig = { + primary: { label: activeSeries.primaryLabel, color: "#2563eb" }, + secondary: { label: activeSeries.secondaryLabel, color: activeSeries.secondaryColor }, + }; + + const formatTick = (value: number) => translate("overview.trendYAxisTick", { count: value }); + + let sandboxBadge: React.ReactNode = null; + if (tab === "containers" && sandboxStatus) { + if (!sandboxStatus.enabled) { + sandboxBadge = ( + + {translate("overview.sandboxLocal")} + + ); + } else if (sandboxStatus.available) { + sandboxBadge = ( + + {translate("overview.sandboxDocker", { runtime: sandboxStatus.runtime || "runc" })} + + ); + } else { + sandboxBadge = ( + + {translate("overview.sandboxUnavailable")} + + ); + } + } + + let footerSummary: string; + let footerHref: string; + let footerLinkLabel: string; + + if (tab === "findings") { + footerSummary = translate("overview.trendFooterFindings", { + total: summary.windowFindings, + highCrit: summary.windowHighCrit, + closed: summary.windowClosedFindings, + }); + footerHref = "/function/findings"; + footerLinkLabel = translate("overview.trendLinkFindings"); + } else if (tab === "containers") { + footerSummary = translate("overview.trendFooterContainers", { + created: summary.windowContainersCreated, + running: summary.currentRunningContainers, + stopped: summary.currentStoppedContainers, + }); + footerHref = "/system/sandbox"; + footerLinkLabel = translate("overview.trendLinkContainers"); + } else { + footerSummary = translate("overview.trendFooterLifecycle", { + created: summary.windowTasksCreated, + completed: summary.windowTasksCompleted, + rate: summary.closureRate, + }); + footerHref = "/function/tasks"; + footerLinkLabel = translate("overview.trendLinkLifecycle"); + } + + const tabs: ReadonlyArray<{ id: TrendTab; label: string }> = [ + { id: "findings", label: translate("overview.trendTabFindings") }, + { id: "containers", label: translate("overview.trendTabContainers") }, + { id: "lifecycle", label: translate("overview.trendTabLifecycle") }, + ]; + + return ( + + {/* Header */} +
+
+

{translate("overview.trendTitle")}

+

{translate("overview.trendSubtitle", { days })}

+
+ +
+ {/* Day window switcher */} +
+ {WINDOW_OPTIONS.map((w) => ( + + ))} +
+ + {/* Metric tabs */} +
+ {tabs.map((item) => ( + + ))} +
+
+
+ + {/* Area / Line Trend Chart */} + + + + + + + + + + + Math.max(dataMax, 4)]} + tick={{ fontSize: 11 }} + tickFormatter={formatTick} + /> + { + if (!active || !payload?.length) return null; + const b = payload[0]?.payload as DayBucket | undefined; + if (!b) return null; + + let rows: Array<{ label: string; value: number; color: string }>; + if (tab === "findings") { + rows = [ + { label: translate("overview.trendSeriesFindings"), value: b.findingsTotal, color: "#2563eb" }, + { label: translate("overview.trendSeriesHighCrit"), value: b.findingsHighCrit, color: "#f43f5e" }, + { label: translate("overview.trendSeriesMedLow"), value: b.findingsMedLow, color: "#f59e0b" }, + { label: translate("overview.trendSeriesClosed"), value: b.findingsClosed, color: "#10b981" }, + ]; + } else if (tab === "containers") { + rows = [ + { + label: translate("overview.trendSeriesContainersCreated"), + value: b.containersCreated, + color: "#2563eb", + }, + { + label: translate("overview.trendSeriesContainersRunning"), + value: b.containersRunning, + color: "#10b981", + }, + { + label: translate("overview.trendSeriesTaskContainers"), + value: b.containersTask, + color: "#6366f1", + }, + { + label: translate("overview.trendSeriesSessionContainers"), + value: b.containersSession, + color: "#0ea5e9", + }, + ]; + } else { + rows = [ + { label: translate("overview.trendSeriesTasksCreated"), value: b.tasksCreated, color: "#2563eb" }, + { label: translate("overview.trendSeriesTasksCompleted"), value: b.tasksCompleted, color: "#10b981" }, + { label: translate("overview.trendSeriesFindings"), value: b.findingsTotal, color: "#f59e0b" }, + { label: translate("overview.trendSeriesClosed"), value: b.findingsClosed, color: "#14b8a6" }, + ]; + } + + return ( +
+
+ {b.dayKey} +
+
+ {rows.map((r) => ( +
+ + + {r.label} + + {r.value} +
+ ))} +
+
+ ); + }} + /> + + +
+
+ + {/* Footer */} +
+
+ {footerSummary} + {sandboxBadge} + {tab === "lifecycle" && activeRetests.length > 0 && ( + + + {translate("overview.activeRetests", { count: activeRetests.length })} + + )} +
+ + {footerLinkLabel} + + +
+
+ ); +} diff --git a/web/src/app/(main)/dashboard/page.tsx b/web/src/app/(main)/dashboard/page.tsx index 4720b22..0fe7343 100644 --- a/web/src/app/(main)/dashboard/page.tsx +++ b/web/src/app/(main)/dashboard/page.tsx @@ -28,6 +28,7 @@ import { Progress } from "@/components/ui/progress"; import { useLiveTranslation } from "@/i18n/use-live-translation"; import { api } from "@/lib/api"; import type { + ActiveFindingRetest, Activity, Agent, ConvTokenSummary, @@ -35,6 +36,7 @@ import type { InterceptPending, LLMProfile, MCPServer, + SandboxGlobalStatus, Settings, SkillItem, Stats, @@ -47,6 +49,8 @@ import type { } from "@/lib/types"; import { cn } from "@/lib/utils"; +import { EnvironmentLifecycleRow } from "./_components/environment-lifecycle-row"; + // ── chart constants ─────────────────────────────────────────────────────────── // ── helpers ────────────────────────────────────────────────────────────────── @@ -194,6 +198,8 @@ export default function DashboardPage() { const [tools, setTools] = React.useState([]); const [llmProfiles, setLLMProfiles] = React.useState([]); const [systemMetrics, setSystemMetrics] = React.useState(null); + const [sandboxStatus, setSandboxStatus] = React.useState(null); + const [activeRetests, setActiveRetests] = React.useState([]); React.useEffect(() => { let alive = true; @@ -213,6 +219,49 @@ export default function DashboardPage() { }; }, []); + React.useEffect(() => { + let alive = true; + let loading = false; + const load = async (progressive: boolean) => { + if (loading) return; + loading = true; + try { + const fast = await api.sandboxStatus(!progressive); + if (!alive) return; + setSandboxStatus(fast); + if ( + progressive && + fast.enabled && + Array.isArray(fast.containers) && + fast.containers.some((c) => c.state === "running") + ) { + void api + .sandboxStatus(true) + .then((fresh) => { + if (alive) setSandboxStatus(fresh); + }) + .catch(() => { + /* ignore transient live stats errors */ + }); + } + } catch { + /* retry on the next interval */ + } finally { + loading = false; + } + }; + void load(true); + const timer = setInterval(() => { + if (document.visibilityState === "visible") { + void load(false); + } + }, 10000); + return () => { + alive = false; + clearInterval(timer); + }; + }, []); + // The task list is the most expensive dashboard source. Poll it independently // so a large history cannot hold back every other dashboard panel. React.useEffect(() => { @@ -252,7 +301,7 @@ export default function DashboardPage() { if (loading) return; loading = true; try { - const [findings, stats, settings, pending, activity, tokens, conversationTokens] = await Promise.all([ + const [findings, stats, settings, pending, activity, tokens, conversationTokens, retests] = await Promise.all([ api.findings(), api.stats(), api.settings(), @@ -260,6 +309,7 @@ export default function DashboardPage() { api.activity(undefined, { limit: 30 }), api.tokenStats(), api.conversationTokens(), + api.activeFindingRetests().catch(() => [] as ActiveFindingRetest[]), ]); if (!alive) return; setFindings(findings); @@ -269,6 +319,7 @@ export default function DashboardPage() { setActivity(activity.items); setTokens(tokens.total ?? null); setConvTokens(conversationTokens); + setActiveRetests(retests); } catch { // Preserve stale data and retry on the next interval. } finally { @@ -942,6 +993,14 @@ export default function DashboardPage() { + {/* ── Row 3: 漏洞、容器与生命周期趋势 ── */} + + {/* ── Row 3: 活动流 | 发现 ── */}
{/* 活动流 */} diff --git a/web/src/i18n/i18n.test.cjs b/web/src/i18n/i18n.test.cjs index 9e0607c..a3c4e68 100644 --- a/web/src/i18n/i18n.test.cjs +++ b/web/src/i18n/i18n.test.cjs @@ -138,6 +138,7 @@ test("migrated pages reference existing keys and contain no hardcoded Chinese di "components/approval-execution-focus.tsx", "hooks/use-side-questions.ts", "app/(main)/dashboard/page.tsx", + "app/(main)/dashboard/_components/environment-lifecycle-row.tsx", "app/(main)/system/settings/_components/backup-card.tsx", "app/(main)/system/settings/_components/basic-auth-card.tsx", "app/(main)/system/settings/_components/update-card.tsx", diff --git a/web/src/i18n/overview-messages.ts b/web/src/i18n/overview-messages.ts index c50b781..34fdf33 100644 --- a/web/src/i18n/overview-messages.ts +++ b/web/src/i18n/overview-messages.ts @@ -201,4 +201,43 @@ export const overviewMessages = { ], "overview.requestCount_one": ["{{count}} 次请求", "{{count}} request"], "overview.requestCount_other": ["{{count}} 次请求", "{{count}} requests"], + "overview.trendTitle": ["漏洞、容器与生命周期趋势", "Vulnerability, container & lifecycle trends"], + "overview.trendSubtitle": [ + "{{days}} 日分桶实时聚合 · 悬停查看每个时间桶明细", + "{{days}}-day live bucket aggregation · Hover for bucket details", + ], + "overview.trendDays": ["{{days}}日", "{{days}}d"], + "overview.trendYAxisTick": ["{{count}} 个", "{{count}}"], + "overview.trendTabFindings": ["漏洞出现", "Findings"], + "overview.trendTabContainers": ["容器创建", "Containers"], + "overview.trendTabLifecycle": ["生命周期", "Lifecycle"], + "overview.trendSeriesFindings": ["新增漏洞", "New findings"], + "overview.trendSeriesHighCrit": ["高危及以上", "High & critical"], + "overview.trendSeriesMedLow": ["中/低危", "Medium & low"], + "overview.trendSeriesClosed": ["其中已闭环", "Closed"], + "overview.trendSeriesContainersCreated": ["容器创建", "Containers created"], + "overview.trendSeriesContainersRunning": ["仍在运行", "Still running"], + "overview.trendSeriesTaskContainers": ["任务容器", "Task containers"], + "overview.trendSeriesSessionContainers": ["对话容器", "Chat containers"], + "overview.trendSeriesTasksCreated": ["任务创建", "Tasks created"], + "overview.trendSeriesTasksCompleted": ["任务完成", "Tasks completed"], + "overview.trendFooterFindings": [ + "窗口总计 {{total}} 个漏洞 · 高危及以上 {{highCrit}} 个 · 已闭环 {{closed}} 个", + "Window total: {{total}} findings · {{highCrit}} high/critical · {{closed}} closed", + ], + "overview.trendFooterContainers": [ + "窗口总计 {{created}} 个容器创建 · 运行中 {{running}} 个 · 已停止 {{stopped}} 个", + "Window total: {{created}} created · {{running}} running · {{stopped}} stopped", + ], + "overview.trendFooterLifecycle": [ + "窗口内创建 {{created}} 个任务 · 完成 {{completed}} 个 · 漏洞闭环率 {{rate}}%", + "Window: {{created}} tasks created · {{completed}} completed · {{rate}}% findings closed", + ], + "overview.trendLinkFindings": ["查看发现明细", "View findings"], + "overview.trendLinkContainers": ["查看容器管理", "Manage containers"], + "overview.trendLinkLifecycle": ["查看任务明细", "View tasks"], + "overview.sandboxDocker": ["Docker · {{runtime}}", "Docker · {{runtime}}"], + "overview.sandboxUnavailable": ["Docker 不可用", "Docker unavailable"], + "overview.sandboxLocal": ["本地模式", "Local mode"], + "overview.activeRetests": ["复测中 {{count}}", "{{count}} retesting"], } satisfies Record; diff --git a/web/src/lib/mock/handler.ts b/web/src/lib/mock/handler.ts index 2f936b7..1c52807 100644 --- a/web/src/lib/mock/handler.ts +++ b/web/src/lib/mock/handler.ts @@ -2880,6 +2880,43 @@ function route(m: string, path: string, seg: string[], q: URLSearchParams, b: Re incomplete_script_action: "model", }; if (path === "/intercept/judge" && m === "PUT") return { ok: true }; + if (path === "/sandbox/status" && m === "GET") { + const runningTasks = mockTasks.filter((t) => t.status === "running"); + return { + mode: "docker", + enabled: true, + available: true, + image: "artex-sandbox:latest", + network: "artex-sandbox", + runtime: "runc", + memory_mb: 2048, + cpus: 2, + pids_limit: 256, + shm_size_mb: 512, + auto_stop_on_complete: true, + session_idle_minutes: 20, + containers: runningTasks.slice(0, 3).map((t, idx) => ({ + scope: "task", + owner_id: String(t.id), + owner_title: t.name || t.description, + task_running: true, + name: `artex-sbx-task-${t.id}`, + short_id: `sbx${idx + 1}a9f2`, + image: "artex-sandbox:latest", + state: "running", + active_runs: idx === 0 ? 2 : 1, + cpu_percent: idx === 0 ? 18.4 : 6.2, + mem_usage_bytes: (idx === 0 ? 412 : 228) * 1024 * 1024, + mem_limit_bytes: 2048 * 1024 * 1024, + pids_current: idx === 0 ? 24 : 11, + work_dir_container: "/workspace", + network: "artex-sandbox", + runtime: "runc", + created_at: t.created_at, + })), + }; + } + if (path === "/intercept/judge/usage" && m === "GET") return { calls: 0,