文件
websafe-kb/scripts/lab/dashboard_templates/lovart/assets/app.js

1400 行
57 KiB
JavaScript

const SECTION_META = [
{ id: "overview", label: "总览", path: "/overview/index.html", description: "查看全局指标、最新运行、架构摘要和入口。", icon: "report" },
{ id: "runs", label: "运行", path: "/runs/index.html", description: "查看运行队列、单次运行详情、证据与日志。", icon: "queue" },
{ id: "systems", label: "系统", path: "/systems/index.html", description: "按系统与分类查看覆盖情况和跳转入口。", icon: "systems" },
{ id: "architecture", label: "架构", path: "/architecture/index.html", description: "折叠查看控制面、数据层、授权边界与路由。", icon: "reasoning" },
{ id: "docs", label: "文档", path: "/docs/index.html", description: "集中访问功能文档、设计文档和镜像说明。", icon: "docs" },
{ id: "data", label: "数据", path: "/data/index.html", description: "集中访问 summary、runs、systems 等 JSON 产物。", icon: "json" }
];
const CATEGORY_LABELS = {
cms: "CMS / 内容平台",
ecommerce: "电商系统",
frameworks: "Web 框架与运行时",
servers: "服务器与边界层",
platforms: "开源平台与后台系统"
};
const STATUS_LABELS = {
"verified-real": "真实版本已实证",
"verified-synthetic": "合成靶场已实证",
"blocked-artifact": "制品阻塞",
"blocked-destructive": "破坏性风险阻塞",
"triage-manual": "人工分诊",
suspected: "仅疑似命中",
completed: "已完成",
failed: "失败",
skipped: "已跳过",
planned: "已规划",
unknown: "未知"
};
const ARTIFACT_KIND_LABELS = {
image: "图片",
text: "文本",
link: "链接"
};
const DOC_HUB_ITEMS = [
{ title: "项目功能总览", href: "/docs/project-features.html", description: "项目定位、功能版图、自动化链路和 CLI 入口。", badge: "docs" },
{ title: "前端设计文档", href: "/docs/frontend-dashboard-design.html", description: "工作台布局、交互、折叠逻辑和视觉规范。", badge: "ui" },
{ title: "架构库镜像", href: "/docs/architecture-library.html", description: "当前架构库的结构化镜像页,可直接查看 JSON 真值。", badge: "architecture" },
{ title: "仓库入口镜像", href: "/docs/root-readme.html", description: "根 README 的本地镜像,包含能力矩阵与主入口。", badge: "readme" },
{ title: "授权模型", href: "/docs/authorization-model.html", description: "目标范围、授权模型、最小化验证建议和记录要求。", badge: "scope" },
{ title: "source-map 镜像", href: "/docs/source-map.html", description: "系统覆盖、来源、输出目录和 secure-code 主题真值。", badge: "source-map" },
{ title: "repro-map 镜像", href: "/docs/repro-map.html", description: "默认漏洞家族、浏览器要求和日志策略真值。", badge: "repro-map" },
{ title: "覆盖矩阵镜像", href: "/docs/coverage-matrix.html", description: "当前全库覆盖矩阵的本地镜像。", badge: "coverage" },
{ title: "安全编码索引", href: "/docs/secure-code-index.html", description: "secure-code 修复主题索引镜像。", badge: "secure-code" },
{ title: "设计来源", href: "/docs/design-source.html", description: "Lovart 模板来源、本地化记录和 manifest 镜像。", badge: "vendor" }
];
const DATA_HUB_ITEMS = [
{ title: "summary.json", href: "/summary.json", description: "全局摘要、状态分布、最近失败与系统汇总。", badge: "json" },
{ title: "runs.json", href: "/runs.json", description: "最近运行的结构化详情,可用于 UI 和调试。", badge: "json" },
{ title: "systems.json", href: "/systems.json", description: "系统级覆盖、分类、更新时间和浏览器证据统计。", badge: "json" },
{ title: "advisories.json", href: "/advisories.json", description: "漏洞条目元数据、来源和 secure-code 主题。", badge: "json" },
{ title: "profiles.json", href: "/profiles.json", description: "复现档案元数据、成功判据和 browser assertions。", badge: "json" },
{ title: "architecture.json", href: "/architecture.json", description: "当前架构库的结构化真值。", badge: "json" },
{ title: "Manifest JSON", href: "/assets/design-source.json", description: "Lovart 模板本地 vendor manifest。", badge: "assets" },
{ title: "最新同步摘要", href: "/docs/coverage-matrix.html", description: "覆盖矩阵与本地生成态入口。", badge: "generated" }
];
const state = {
routeSection: resolveRouteSection(),
summary: null,
runs: [],
systems: [],
advisories: {},
profiles: {},
architecture: null,
selectedRunId: null,
selectedArtifact: null,
refreshHandle: null,
refreshMs: 5000,
autoRefresh: true,
filters: {
search: "",
status: "",
category: "",
family: "",
system: ""
},
panels: {
timeline: true,
reasoning: true,
evidence: true,
logs: true,
sources: true,
architecture: true,
run_json: false,
advisory_json: false,
profile_json: false
}
};
const $ = (id) => document.getElementById(id);
const icon = (name, className = "icon") =>
`<svg class="${className}" aria-hidden="true"><use href="/assets/icons.svg#${name}"></use></svg>`;
const statusClass = (status) => ({
"verified-real": "status-pill status-verified-real",
"verified-synthetic": "status-pill status-verified-synthetic",
"blocked-artifact": "status-pill status-blocked-artifact",
"blocked-destructive": "status-pill status-blocked-destructive",
"triage-manual": "status-pill status-triage-manual",
suspected: "status-pill status-suspected",
completed: "status-pill status-verified-real",
failed: "status-pill status-blocked-artifact",
skipped: "status-pill status-triage-manual"
}[status] || "status-pill status-default");
function resolveRouteSection() {
const parts = window.location.pathname.split("/").filter(Boolean);
const first = parts[0] || "";
if (!first || first === "index.html" || first === "overview") return "overview";
if (SECTION_META.some((section) => section.id === first)) return first;
return "overview";
}
function currentOverviewAlias() {
return window.location.pathname === "/" || window.location.pathname === "/index.html";
}
function routePath(sectionId) {
if (sectionId === "overview" && currentOverviewAlias()) return window.location.pathname || "/index.html";
const section = SECTION_META.find((item) => item.id === sectionId);
return section ? section.path : "/overview/index.html";
}
function escapeHtml(value) {
return String(value ?? "")
.replaceAll("&", "&amp;")
.replaceAll("<", "&lt;")
.replaceAll(">", "&gt;")
.replaceAll('"', "&quot;");
}
function formatStatus(value) {
return STATUS_LABELS[value] || String(value || "unknown").replaceAll("-", " ");
}
function formatCategory(value) {
return CATEGORY_LABELS[value] || String(value || "未分类");
}
function formatDateTime(value) {
if (!value) return "-";
const date = new Date(value);
if (Number.isNaN(date.getTime())) return String(value);
return date.toLocaleString("zh-CN", {
hour12: false,
year: "numeric",
month: "2-digit",
day: "2-digit",
hour: "2-digit",
minute: "2-digit",
second: "2-digit"
});
}
function timeAgo(value) {
if (!value) return "-";
const diff = Date.now() - new Date(value).getTime();
if (Number.isNaN(diff)) return String(value);
const seconds = Math.floor(diff / 1000);
if (seconds <= 5) return "刚刚";
if (seconds < 60) return `${seconds} 秒前`;
const minutes = Math.floor(seconds / 60);
if (minutes < 60) return `${minutes} 分钟前`;
const hours = Math.floor(minutes / 60);
if (hours < 24) return `${hours} 小时前`;
const days = Math.floor(hours / 24);
return `${days} 天前`;
}
function distinct(values) {
return [...new Set(values.filter(Boolean))].sort();
}
async function fetchJson(url) {
const response = await fetch(`${url}?t=${Date.now()}`, { cache: "no-store" });
if (!response.ok) throw new Error(`${url} -> ${response.status}`);
return response.json();
}
function sectionMeta(sectionId = state.routeSection) {
return SECTION_META.find((item) => item.id === sectionId) || SECTION_META[0];
}
function applyUrlState() {
const params = new URLSearchParams(window.location.search);
state.filters.search = params.get("search") || "";
state.filters.status = params.get("status") || "";
state.filters.category = params.get("category") || "";
state.filters.family = params.get("family") || "";
state.filters.system = params.get("system") || "";
state.selectedRunId = params.get("run") || null;
}
function buildUrl(sectionId = state.routeSection, overrides = {}) {
const nextFilters = { ...state.filters };
for (const [key, value] of Object.entries(overrides)) {
if (key === "run") continue;
if (value === null || value === undefined || value === "") {
delete nextFilters[key];
nextFilters[key] = "";
} else {
nextFilters[key] = String(value);
}
}
const nextRunId = Object.prototype.hasOwnProperty.call(overrides, "run")
? (overrides.run ? String(overrides.run) : "")
: (state.selectedRunId || "");
const params = new URLSearchParams();
if (["overview", "runs", "systems"].includes(sectionId)) {
if (nextFilters.search) params.set("search", nextFilters.search);
if (nextFilters.status && sectionId !== "systems") params.set("status", nextFilters.status);
if (nextFilters.category) params.set("category", nextFilters.category);
if (nextFilters.family && sectionId !== "systems") params.set("family", nextFilters.family);
if (nextFilters.system) params.set("system", nextFilters.system);
}
if (sectionId === "runs" && nextRunId) params.set("run", nextRunId);
const query = params.toString();
return `${routePath(sectionId)}${query ? `?${query}` : ""}`;
}
function updateUrl() {
const nextUrl = buildUrl();
const currentUrl = `${window.location.pathname}${window.location.search}`;
if (nextUrl !== currentUrl) {
window.history.replaceState({}, "", nextUrl);
}
}
function navigateToSection(sectionId, overrides = {}) {
window.location.assign(buildUrl(sectionId, overrides));
}
function sumStatuses(predicate) {
return Object.entries(state.summary?.statuses || {})
.filter(([key]) => predicate(key))
.reduce((sum, [, value]) => sum + Number(value || 0), 0);
}
function categoryOptions() {
return distinct(state.systems.map((system) => system.category));
}
function familyOptions() {
return distinct(state.runs.map((run) => run.profile_meta?.vuln_family || ""));
}
function metricCards() {
const successCount = Number(state.summary?.statuses?.["verified-real"] || 0) + Number(state.summary?.statuses?.["verified-synthetic"] || 0);
const blockedCount = sumStatuses((key) => key.startsWith("blocked"));
const inProgressCount = Math.max(Number(state.summary?.run_count || 0) - successCount - blockedCount, 0);
return [
{
label: "运行总数",
value: state.summary?.run_count || 0,
note: `已索引漏洞条目 ${state.summary?.advisory_count || 0}`,
color: "var(--accent-purple)",
iconName: "report"
},
{
label: "实证成功",
value: successCount,
note: "真实版本 + 合成靶场",
color: "var(--accent-green)",
iconName: "shield"
},
{
label: "当前阻塞",
value: blockedCount,
note: "制品阻塞或破坏性风险阻塞",
color: "var(--accent-red)",
iconName: "failure"
},
{
label: "待处理 / 进行中",
value: inProgressCount,
note: "人工分诊、待补证据或未完成实证",
color: "var(--accent-blue)",
iconName: "timeline"
}
];
}
function renderMetrics() {
$("metricCards").innerHTML = metricCards()
.map(
(card) => `
<article class="metric-card" style="--metric-color:${card.color}">
<div class="metric-label">${icon(card.iconName)}<span>${escapeHtml(card.label)}</span></div>
<div class="metric-value">${escapeHtml(card.value)}</div>
<div class="metric-note">${escapeHtml(card.note)}</div>
</article>
`
)
.join("");
}
function renderSyncState(kind, title, detail) {
$("syncState").innerHTML = `
${icon("sync", "icon icon-sync")}
<div>
<strong>${escapeHtml(title)}</strong>
<span>${escapeHtml(detail)}</span>
</div>
`;
$("syncState").dataset.kind = kind;
}
function renderSectionNav() {
const active = state.routeSection;
$("sectionNav").innerHTML = SECTION_META
.map((section) => `
<a class="nav-pill ${section.id === active ? "is-active" : ""}" href="${escapeHtml(buildUrl(section.id, section.id === "runs" ? { run: state.selectedRunId || null } : {}))}" data-section-id="${escapeHtml(section.id)}">
<span class="nav-pill-top">${icon(section.icon)}<strong>${escapeHtml(section.label)}</strong></span>
<span class="nav-pill-copy">${escapeHtml(section.description)}</span>
</a>
`)
.join("");
}
function renderChipRow(label, key, options, formatter) {
return `
<section class="menu-row">
<div class="menu-row-head">
<strong>${escapeHtml(label)}</strong>
<span>${escapeHtml(options.length)} 项</span>
</div>
<div class="chip-strip">
<button class="menu-chip ${state.filters[key] ? "" : "is-active"}" type="button" data-filter-key="${escapeHtml(key)}" data-filter-value="">
全部
</button>
${options
.map(
(value) => `
<button class="menu-chip ${state.filters[key] === value ? "is-active" : ""}" type="button" data-filter-key="${escapeHtml(key)}" data-filter-value="${escapeHtml(value)}">
${escapeHtml(formatter(value))}
</button>
`
)
.join("")}
</div>
</section>
`;
}
function renderTopMenus() {
const meta = sectionMeta();
const routeLine = `
<div class="route-note">
<div>
<strong>${escapeHtml(meta.label)}</strong>
<span>${escapeHtml(meta.description)}</span>
</div>
<div class="tag-row">
<span class="tag">当前地址 ${escapeHtml(window.location.pathname)}</span>
${window.location.search ? `<span class="tag">${escapeHtml(window.location.search)}</span>` : ""}
</div>
</div>
`;
const rows = [];
if (["overview", "runs"].includes(state.routeSection)) {
rows.push(renderChipRow("状态筛选", "status", distinct(state.runs.map((item) => item.verification_status)), formatStatus));
rows.push(renderChipRow("系统板块", "category", categoryOptions(), formatCategory));
rows.push(renderChipRow("漏洞家族", "family", familyOptions(), (value) => value));
} else if (state.routeSection === "systems") {
rows.push(renderChipRow("系统板块", "category", categoryOptions(), formatCategory));
}
if (state.filters.system && ["overview", "runs", "systems"].includes(state.routeSection)) {
rows.push(`
<section class="menu-row">
<div class="menu-row-head">
<strong>已选系统</strong>
<span>精确筛选</span>
</div>
<div class="chip-strip">
<button class="menu-chip is-active" type="button" data-filter-key="system" data-filter-value="${escapeHtml(state.filters.system)}">
${escapeHtml(state.filters.system)}
</button>
<button class="menu-chip menu-chip-muted" type="button" data-filter-key="system" data-filter-value="">
清除系统筛选
</button>
</div>
</section>
`);
}
if (["overview", "runs", "systems"].includes(state.routeSection)) {
rows.push(`
<section class="menu-row menu-row-compact">
<div class="menu-row-head">
<strong>筛选操作</strong>
<span>URL 会自动同步</span>
</div>
<div class="chip-strip">
<button class="menu-chip menu-chip-muted" type="button" data-clear-filters="1">清空全部筛选</button>
${state.routeSection !== "runs" ? `<a class="menu-chip menu-chip-link" href="${escapeHtml(buildUrl("runs"))}">进入运行中心</a>` : ""}
${state.routeSection !== "systems" ? `<a class="menu-chip menu-chip-link" href="${escapeHtml(buildUrl("systems"))}">进入系统分组</a>` : ""}
</div>
</section>
`);
}
$("topMenus").innerHTML = `${routeLine}${rows.join("")}`;
}
function filteredRuns() {
return state.runs.filter((item) => {
if (state.filters.system && item.system_id !== state.filters.system) return false;
if (state.filters.status && item.verification_status !== state.filters.status) return false;
if (state.filters.category && item.advisory_meta?.category !== state.filters.category) return false;
if (state.filters.family && item.profile_meta?.vuln_family !== state.filters.family) return false;
if (!state.filters.search) return true;
const haystack = [
item.run_id,
item.advisory_id,
item.system_id,
item.repro_profile_id,
item.profile_meta?.vuln_family || "",
item.advisory_meta?.title || "",
item.advisory_meta?.summary || ""
]
.join(" ")
.toLowerCase();
return haystack.includes(state.filters.search);
});
}
function filteredSystems() {
return state.systems.filter((system) => {
if (state.filters.system && system.system_id !== state.filters.system) return false;
if (state.filters.category && system.category !== state.filters.category) return false;
if (!state.filters.search) return true;
const haystack = [
system.system_id,
system.display_name || "",
formatCategory(system.category)
]
.join(" ")
.toLowerCase();
return haystack.includes(state.filters.search);
});
}
function recentFailures(limit = 6) {
return (state.summary?.recent_failures || []).slice(0, limit);
}
function recentRuns(limit = 8) {
return filteredRuns().slice(0, limit);
}
function renderSearchSection(countLabel, placeholder) {
const tags = [
state.filters.status ? `状态: ${formatStatus(state.filters.status)}` : "",
state.filters.category ? `板块: ${formatCategory(state.filters.category)}` : "",
state.filters.family ? `家族: ${state.filters.family}` : "",
state.filters.system ? `系统: ${state.filters.system}` : ""
].filter(Boolean);
return `
<section class="sidebar-section">
<div class="section-header">
<span>${icon("filter")}检索与范围</span>
<span class="section-badge">${escapeHtml(countLabel)}</span>
</div>
<label class="field">
<span>搜索</span>
<div class="search-box">
${icon("search")}
<input id="searchInput" type="text" value="${escapeHtml(state.filters.search)}" placeholder="${escapeHtml(placeholder)}">
</div>
</label>
${tags.length ? `<div class="tag-row" style="margin-top:12px;">${tags.map((tag) => `<span class="tag">${escapeHtml(tag)}</span>`).join("")}</div>` : `<div class="muted" style="margin-top:12px;">当前未启用额外筛选。</div>`}
</section>
`;
}
function renderFailureCards(items) {
return items.length
? items
.map(
(item) => `
<article class="failure-card">
<div class="timeline-head">
<strong class="failure-title">${escapeHtml(item.run_id)}</strong>
<span class="${statusClass(item.status)}">${escapeHtml(formatStatus(item.status))}</span>
</div>
<div class="muted" style="margin-top:8px;">${escapeHtml(item.title || item.advisory_id)}</div>
<div class="failure-reason" style="margin-top:8px;">${escapeHtml(item.blocked_reason || "未提供失败原因。")}</div>
</article>
`
)
.join("")
: `<div class="empty-state">当前没有最近失败记录。</div>`;
}
function renderRunList(items, emptyText) {
return items.length
? items
.map((item) => {
const active = item.run_id === state.selectedRunId && state.routeSection === "runs" ? "is-active" : "";
const browserState = item.browser_evidence?.present ? "已采集" : (item.browser_evidence?.required ? "必需待补" : "可选");
const artifactCount = (item.artifact_groups || []).reduce((sum, group) => sum + Number(group.count || 0), 0);
const lead = item.reasoning_lines?.[0] || item.blocked_reason || item.advisory_meta?.summary || "";
return `
<button class="run-card ${active}" type="button" data-run-id="${escapeHtml(item.run_id)}">
<div class="run-topline">
<strong class="run-title">${escapeHtml(item.run_id)}</strong>
<span class="${statusClass(item.verification_status)}">${escapeHtml(formatStatus(item.verification_status))}</span>
</div>
<div class="muted" style="margin-top:8px;">${escapeHtml(item.advisory_meta?.title || item.advisory_id)}</div>
<div class="run-meta" style="margin-top:8px;">
<span>${escapeHtml(item.system_id)}</span>
<span>${escapeHtml(item.profile_meta?.vuln_family || item.repro_profile_id)}</span>
<span>${escapeHtml(timeAgo(item.finished_at))}</span>
</div>
<div class="tag-row" style="margin-top:10px;">
<span class="tag">证据 ${escapeHtml(artifactCount)}</span>
<span class="tag">浏览器 ${escapeHtml(browserState)}</span>
</div>
<div class="muted" style="margin-top:10px;">${escapeHtml(lead)}</div>
</button>
`;
})
.join("")
: `<div class="empty-state">${escapeHtml(emptyText)}</div>`;
}
function renderSystemCards(items, compact = false) {
return items.length
? items
.map((system) => {
const total = Math.max(Number(system.total || 0), 1);
const verified = Number(system.verified_real || 0) + Number(system.verified_synthetic || 0);
const coverage = Math.round((verified / total) * 100);
return `
<article class="system-card ${compact ? "system-card-compact" : ""}">
<div class="timeline-head">
<strong class="system-title">${escapeHtml(system.display_name || system.system_id)}</strong>
<span class="section-chip">${escapeHtml(formatCategory(system.category || ""))}</span>
</div>
<div class="muted">${escapeHtml(system.system_id)} · 最近更新 ${escapeHtml(formatDateTime(system.latest_update || "-"))}</div>
<div class="tag-row" style="margin-top:10px;">
<span class="tag">真实 ${escapeHtml(system.verified_real || 0)}</span>
<span class="tag">合成 ${escapeHtml(system.verified_synthetic || 0)}</span>
<span class="tag">阻塞 ${escapeHtml(system.blocked || 0)}</span>
</div>
<div class="meter"><span style="--fill:${coverage}%"></span></div>
<div class="detail-actions" style="margin-top:12px;">
<button class="button button-secondary button-small" type="button" data-filter-key="system" data-filter-value="${escapeHtml(system.system_id)}">锁定系统</button>
<a class="button button-secondary button-small" href="${escapeHtml(buildUrl("runs", { system: system.system_id, run: null }))}">查看运行</a>
</div>
</article>
`;
})
.join("")
: `<div class="empty-state">当前筛选下没有系统数据。</div>`;
}
function renderHubCards(items) {
return `
<div class="hub-grid">
${items
.map(
(item) => `
<a class="hub-card" href="${escapeHtml(item.href)}" target="_blank" rel="noreferrer">
<div class="timeline-head">
<strong>${escapeHtml(item.title)}</strong>
${item.badge ? `<span class="section-chip">${escapeHtml(item.badge)}</span>` : ""}
</div>
<div class="plan-copy">${escapeHtml(item.description)}</div>
</a>
`
)
.join("")}
</div>
`;
}
function renderSidebar() {
const sidebar = $("sidebar");
const filteredRunItems = filteredRuns();
const filteredSystemItems = filteredSystems();
const architectureSections = state.architecture?.sections || [];
if (state.routeSection === "runs") {
sidebar.innerHTML = [
renderSearchSection(`${filteredRunItems.length} 条运行`, "搜索 run id、漏洞条目、标题、系统、家族"),
`
<section class="sidebar-section">
<div class="section-header">
<span>${icon("failure")}最近失败</span>
</div>
<div class="failure-list">${renderFailureCards(recentFailures(5))}</div>
</section>
`,
`
<section class="sidebar-section sidebar-section-fill">
<div class="section-header">
<span>${icon("queue")}运行队列</span>
<span class="section-badge">${escapeHtml(filteredRunItems.length)}</span>
</div>
<div class="run-list">${renderRunList(filteredRunItems, "当前筛选条件下没有匹配的运行。")}</div>
</section>
`
].join("");
return;
}
if (state.routeSection === "systems") {
sidebar.innerHTML = [
renderSearchSection(`${filteredSystemItems.length} 个系统`, "搜索系统名、display name、板块"),
`
<section class="sidebar-section sidebar-section-fill">
<div class="section-header">
<span>${icon("systems")}系统目录</span>
<span class="section-badge">${escapeHtml(filteredSystemItems.length)}</span>
</div>
<div class="system-stats">${renderSystemCards(filteredSystemItems.slice(0, 18), true)}</div>
</section>
`
].join("");
return;
}
if (state.routeSection === "architecture") {
sidebar.innerHTML = `
<section class="sidebar-section">
<div class="section-header">
<span>${icon("systems")}架构分区</span>
<span class="section-badge">${escapeHtml(architectureSections.length)}</span>
</div>
<div class="hub-grid">
${architectureSections
.map(
(section) => `
<article class="hub-card hub-card-static">
<strong>${escapeHtml(section.title)}</strong>
<div class="plan-copy">${escapeHtml(section.summary || "当前分区无额外摘要。")}</div>
</article>
`
)
.join("")}
</div>
</section>
`;
return;
}
if (state.routeSection === "docs") {
sidebar.innerHTML = `
<section class="sidebar-section sidebar-section-fill">
<div class="section-header">
<span>${icon("docs")}文档目录</span>
<span class="section-badge">${escapeHtml(DOC_HUB_ITEMS.length)}</span>
</div>
${renderHubCards(DOC_HUB_ITEMS)}
</section>
`;
return;
}
if (state.routeSection === "data") {
sidebar.innerHTML = `
<section class="sidebar-section sidebar-section-fill">
<div class="section-header">
<span>${icon("json")}数据入口</span>
<span class="section-badge">${escapeHtml(DATA_HUB_ITEMS.length)}</span>
</div>
${renderHubCards(DATA_HUB_ITEMS)}
</section>
`;
return;
}
sidebar.innerHTML = [
renderSearchSection(`${filteredRunItems.length} 条运行`, "搜索运行、漏洞条目、标题、系统、家族"),
`
<section class="sidebar-section">
<div class="section-header">
<span>${icon("failure")}最近失败</span>
</div>
<div class="failure-list">${renderFailureCards(recentFailures(4))}</div>
</section>
`,
`
<section class="sidebar-section">
<div class="section-header">
<span>${icon("queue")}最新运行</span>
<a class="section-chip" href="${escapeHtml(buildUrl("runs"))}">进入运行中心</a>
</div>
<div class="run-list run-list-compact">${renderRunList(recentRuns(6), "暂无运行数据。")}</div>
</section>
`,
`
<section class="sidebar-section sidebar-section-fill">
<div class="section-header">
<span>${icon("systems")}系统概览</span>
<a class="section-chip" href="${escapeHtml(buildUrl("systems"))}">进入系统分组</a>
</div>
<div class="system-stats">${renderSystemCards(filteredSystemItems.slice(0, 8), true)}</div>
</section>
`
].join("");
}
function renderPanel(panelKey, title, meta, iconName, content) {
const open = state.panels[panelKey] !== false;
return `
<section class="panel ${open ? "" : "is-collapsed"}" data-panel="${panelKey}">
<button class="panel-header" type="button" data-panel-toggle="${panelKey}">
<span class="panel-title">${icon(iconName)}<span>${escapeHtml(title)}</span></span>
<span class="panel-meta">
<span>${meta}</span>
${icon("chevron", "icon panel-chevron")}
</span>
</button>
<div class="panel-content">
<div class="panel-content-inner">${content}</div>
</div>
</section>
`;
}
function renderArchitectureFields(fields = []) {
if (!fields.length) return "";
return `
<div class="arch-field-grid">
${fields
.map(
(field) => `
<article class="arch-field">
<span class="arch-field-label">${escapeHtml(field.label || "-")}</span>
<div class="arch-field-value">${escapeHtml(field.value || "-")}</div>
</article>
`
)
.join("")}
</div>
`;
}
function renderArchitectureStats(stats = []) {
if (!stats.length) return "";
return `
<div class="arch-stat-grid">
${stats
.map(
(item) => `
<article class="arch-stat">
<span class="arch-stat-label">${escapeHtml(item.label || "-")}</span>
<strong class="arch-stat-value">${escapeHtml(item.value || "-")}</strong>
</article>
`
)
.join("")}
</div>
`;
}
function renderArchitectureLinks(links = []) {
if (!links.length) return "";
return `
<div class="arch-link-grid">
${links
.map(
(linkItem) => `
<a class="arch-link-card" href="${escapeHtml(linkItem.href || "#")}" target="_blank" rel="noreferrer">
<span class="arch-link-label">${escapeHtml(linkItem.label || "打开链接")}</span>
<span class="arch-link-copy">${escapeHtml(linkItem.description || linkItem.href || "")}</span>
</a>
`
)
.join("")}
</div>
`;
}
function renderArchitectureNode(node, depth = 0) {
if (!node) return "";
const children = (node.items || []).map((item) => renderArchitectureNode(item, depth + 1)).join("");
const fields = renderArchitectureFields(node.fields || []);
const stats = renderArchitectureStats(node.stats || []);
const links = renderArchitectureLinks(node.links || []);
const badges = (node.badges || []).map((badge) => `<span class="tag">${escapeHtml(badge)}</span>`).join("");
const hasBody = Boolean(children || fields || stats || links || node.summary || badges);
const summaryBlock = `
<div class="arch-summary-main">
<strong class="arch-title">${escapeHtml(node.title || "未命名节点")}</strong>
${node.summary ? `<span class="arch-summary-copy">${escapeHtml(node.summary)}</span>` : ""}
</div>
<div class="arch-summary-meta">
${node.items?.length ? `<span class="section-chip">${escapeHtml(node.items.length)} 个子项</span>` : ""}
${node.fields?.length ? `<span class="section-chip">${escapeHtml(node.fields.length)} 个字段</span>` : ""}
${node.links?.length ? `<span class="section-chip">${escapeHtml(node.links.length)} 个链接</span>` : ""}
</div>
`;
if (!hasBody) {
return `<article class="arch-leaf" data-depth="${escapeHtml(depth)}">${summaryBlock}</article>`;
}
const openAttr = node.open === false ? "" : "open";
return `
<details class="arch-node" data-depth="${escapeHtml(depth)}" ${openAttr}>
<summary class="arch-summary">${summaryBlock}</summary>
<div class="arch-body">
${badges ? `<div class="tag-row arch-badges">${badges}</div>` : ""}
${stats}
${fields}
${links}
${children ? `<div class="arch-children">${children}</div>` : ""}
</div>
</details>
`;
}
function renderArchitecturePanel() {
const architecture = state.architecture;
if (!architecture) {
return renderPanel("architecture", "当前架构库", "未生成", "systems", `<div class="empty-state">尚未找到架构 JSON,请先执行渲染命令。</div>`);
}
const sections = architecture.sections || [];
const content = `
<div class="callout architecture-callout">
<strong>${escapeHtml(architecture.title || "当前架构库")}</strong>
<div class="plan-copy">${escapeHtml(architecture.summary || "当前工作台的结构化真值视图。")}</div>
<div class="tag-row" style="margin-top:10px;">
<span class="tag">生成时间 ${escapeHtml(formatDateTime(architecture.generated_at))}</span>
<a class="tag" href="/architecture.json" target="_blank" rel="noreferrer">架构 JSON</a>
<a class="tag" href="/docs/architecture-library.html" target="_blank" rel="noreferrer">镜像页</a>
<a class="tag" href="/docs/root-readme.html" target="_blank" rel="noreferrer">仓库入口镜像</a>
</div>
</div>
<div class="architecture-tree">
${sections.length ? sections.map((section) => renderArchitectureNode(section, 0)).join("") : `<div class="empty-state">架构库目前没有可展示的分区。</div>`}
</div>
`;
return renderPanel("architecture", "当前架构库", `${sections.length} 个分区`, "systems", content);
}
function defaultArtifact(run) {
const preference = ["attack", "requests", "container", "browser", "baseline", "compose", "reports"];
for (const key of preference) {
const group = (run.artifact_groups || []).find((item) => item.key === key && item.items?.length);
if (!group) continue;
const textItem = group.items.find((item) => item.kind === "text");
return textItem || group.items[0];
}
return null;
}
async function openArtifact(href, label, kind) {
state.selectedArtifact = { href, label, kind };
document.querySelectorAll(".artifact-button").forEach((button) => {
button.classList.toggle("is-active", button.dataset.href === href);
});
const labelNode = $("viewerLabel");
const metaNode = $("viewerMeta");
const openNode = $("viewerOpen");
const viewer = $("viewerFrame");
if (!labelNode || !metaNode || !openNode || !viewer) return;
labelNode.textContent = label;
metaNode.textContent = href;
openNode.href = href;
try {
if (kind === "image") {
viewer.innerHTML = `<img src="${escapeHtml(href)}?t=${Date.now()}" alt="${escapeHtml(label)}">`;
return;
}
if (href.endsWith(".html")) {
viewer.innerHTML = `<iframe src="${escapeHtml(href)}?t=${Date.now()}"></iframe>`;
return;
}
const response = await fetch(`${href}?t=${Date.now()}`, { cache: "no-store" });
if (!response.ok) throw new Error(`${href} -> ${response.status}`);
const text = await response.text();
let formatted = text;
if (href.endsWith(".json")) {
try {
formatted = JSON.stringify(JSON.parse(text), null, 2);
} catch (_error) {
}
}
viewer.innerHTML = `<pre>${escapeHtml(formatted)}</pre>`;
} catch (error) {
viewer.innerHTML = `<pre>加载产物失败:${escapeHtml(error.message)}</pre>`;
}
}
function renderRunWorkspace() {
const runs = filteredRuns();
if (!runs.length) {
return `
<div class="workspace-empty">
${icon("shield", "icon icon-xl")}
<h2>当前没有匹配运行</h2>
<p class="empty-copy">请先清空筛选,或者从系统分组页进入某个系统的运行中心。</p>
</div>
${renderArchitecturePanel()}
`;
}
if (!state.selectedRunId || !runs.some((item) => item.run_id === state.selectedRunId)) {
state.selectedRunId = runs[0].run_id;
}
const run = runs.find((item) => item.run_id === state.selectedRunId);
const advisory = run.advisory_meta || {};
const profile = run.profile_meta || {};
const screenshotItems = ((run.artifact_groups || []).find((group) => group.key === "browser")?.items || []).filter((item) => item.kind === "image");
const artifactCount = (run.artifact_groups || []).reduce((sum, group) => sum + Number(group.count || 0), 0);
const browserStatus = run.browser_evidence?.present ? "已采集" : (run.browser_evidence?.required ? "必需待补" : "可选");
const progress = {
completed: 0,
skipped: 0,
failed: 0,
blocked: 0,
planned: 0,
other: 0
};
(run.timeline || []).forEach((item) => {
if (String(item.status || "").startsWith("blocked")) progress.blocked += 1;
else if (Object.prototype.hasOwnProperty.call(progress, item.status || "")) progress[item.status] += 1;
else progress.other += 1;
});
const timelineRows = (run.timeline || [])
.map((item) => `
<article class="timeline-item ${timelineTone(item.status)}">
<span class="timeline-dot"></span>
<div class="timeline-head">
<strong>${escapeHtml(item.step || "-")}</strong>
<span class="timeline-time">${escapeHtml(formatDateTime(item.at || "-"))}</span>
</div>
<div class="${statusClass(item.status || "default")}" style="margin-top:8px;">${escapeHtml(formatStatus(item.status || "unknown"))}</div>
<div class="timeline-detail">${escapeHtml(item.detail || "-")}</div>
</article>
`)
.join("") || `<div class="empty-state">当前运行没有记录时间线。</div>`;
const reasoningCards = [
{ label: "概要", copy: advisory.summary || "当前漏洞条目没有摘要。" },
{ label: "成功判据", copy: (profile.success_criteria || []).join(" | ") || "当前复现档案没有定义成功判据。" },
{ label: "Seed / 攻击思路", copy: (run.reasoning_lines || []).join("\n\n") || "当前运行没有记录思路说明。" },
{ label: "允许目标", copy: (profile.allowed_target_types || []).join(", ") || "当前复现档案没有声明允许目标类型。" }
];
const evidenceContent = `
<div class="artifact-groups">
${(run.artifact_groups || [])
.map(
(group) => `
<section class="artifact-group">
<h3>${escapeHtml(group.label)} · ${escapeHtml(group.count)}</h3>
<div class="artifact-grid">
${group.items
.map(
(item) => `
<button class="artifact-button" type="button" data-artifact data-href="${escapeHtml(item.href)}" data-kind="${escapeHtml(item.kind)}" data-label="${escapeHtml(item.label)}">
<span>${escapeHtml(item.label)}</span>
<span class="artifact-kind">${escapeHtml(ARTIFACT_KIND_LABELS[item.kind] || item.kind)}</span>
</button>
`
)
.join("")}
</div>
</section>
`
)
.join("")}
${screenshotItems.length ? `<div class="gallery">${screenshotItems.map((item) => `
<button class="artifact-button gallery-card" type="button" data-artifact data-href="${escapeHtml(item.href)}" data-kind="${escapeHtml(item.kind)}" data-label="${escapeHtml(item.label)}">
<img src="${escapeHtml(item.href)}" alt="${escapeHtml(item.label)}">
<span>${escapeHtml(item.label)}</span>
</button>`).join("")}</div>` : ""}
</div>
`;
const sourceLinks = [
advisory.official_source_url
? `<a href="${escapeHtml(advisory.official_source_url)}" target="_blank" rel="noreferrer">${escapeHtml(advisory.official_source_url)}</a>`
: `<span class="muted">当前漏洞条目没有关联官方来源。</span>`,
...(advisory.secondary_source_urls || []).map((url) => `<a href="${escapeHtml(url)}" target="_blank" rel="noreferrer">${escapeHtml(url)}</a>`)
].join("");
const rawRunContent = `<article class="json-card"><pre>${escapeHtml(JSON.stringify(run, null, 2))}</pre></article>`;
const rawAdvisoryContent = `<article class="json-card"><pre>${escapeHtml(JSON.stringify(advisory, null, 2))}</pre></article>`;
const rawProfileContent = `<article class="json-card"><pre>${escapeHtml(JSON.stringify(profile, null, 2))}</pre></article>`;
return `
<section class="detail-hero">
<div class="detail-topline">
<span class="${statusClass(run.verification_status)}">${escapeHtml(formatStatus(run.verification_status))}</span>
<div class="tag-row">
<span class="tag">${escapeHtml(run.system_id)}</span>
<span class="tag">${escapeHtml(run.repro_profile_id)}</span>
<span class="tag">${escapeHtml(run.verification_mode || "-")}</span>
<span class="tag">${escapeHtml(run.target_env || "-")}</span>
</div>
</div>
<h2 class="detail-title">${escapeHtml(advisory.title || run.advisory_id)}</h2>
<div class="detail-subtitle">${escapeHtml(advisory.summary || "当前漏洞条目没有摘要。")}</div>
<div class="detail-actions">
<a class="button button-primary" href="${escapeHtml(run.dashboard_refs.report_html)}" target="_blank" rel="noreferrer">${icon("report")}<span>HTML 报告</span></a>
<a class="button button-secondary" href="${escapeHtml(run.dashboard_refs.report_md)}" target="_blank" rel="noreferrer">${icon("markdown")}<span>Markdown 报告</span></a>
<a class="button button-secondary" href="${escapeHtml(run.dashboard_refs.bundle)}" target="_blank" rel="noreferrer">${icon("json")}<span>运行 JSON</span></a>
</div>
<div class="detail-stat-grid">
<article class="detail-stat">
<strong>时间线步骤</strong>
<span>${escapeHtml(run.timeline?.length || 0)}</span>
</article>
<article class="detail-stat">
<strong>证据数量</strong>
<span>${escapeHtml(artifactCount)}</span>
</article>
<article class="detail-stat">
<strong>浏览器证据</strong>
<span>${escapeHtml(browserStatus)}</span>
</article>
<article class="detail-stat">
<strong>完成时间</strong>
<span>${escapeHtml(timeAgo(run.finished_at))}</span>
</article>
</div>
</section>
${renderPanel("timeline", "进度时间线", `${escapeHtml(run.timeline?.length || 0)}`, "timeline", `
<div class="progress-bar">${progressSegments(progress).bar}</div>
<div class="progress-legend">${progressSegments(progress).legend}</div>
<div class="timeline">${timelineRows}</div>
`)}
${renderPanel("reasoning", "攻击方案与推理", escapeHtml(profile.vuln_family || "未定义"), "reasoning", `
${run.blocked_reason ? `<div class="callout"><strong>失败原因</strong><div class="plan-copy">${escapeHtml(run.blocked_reason)}</div></div>` : ""}
<div class="tag-row" style="margin-bottom:14px;">
<span class="tag">漏洞家族 ${escapeHtml(profile.vuln_family || "未定义")}</span>
<span class="tag">清理策略 ${escapeHtml(profile.cleanup_policy || "-")}</span>
<span class="tag">破坏性风险 ${escapeHtml(profile.destructive_risk || "-")}</span>
<span class="tag">制品模式 ${escapeHtml(run.artifact_mode || "-")}</span>
</div>
<div class="plan-grid">
${reasoningCards.map((card) => `
<article class="plan-card">
<span class="plan-label">${escapeHtml(card.label)}</span>
<div class="plan-copy">${escapeHtml(card.copy)}</div>
</article>
`).join("")}
</div>
`)}
${renderPanel("evidence", "证据浏览器", `${escapeHtml(run.artifact_groups?.length || 0)}`, "evidence", evidenceContent)}
${renderPanel("logs", "实时日志查看器", state.selectedArtifact ? "已选产物" : "等待选择", "logs", `
<div class="viewer-card">
<div class="viewer-toolbar">
<div>
<div id="viewerLabel" class="viewer-label">${escapeHtml(state.selectedArtifact?.label || "选择一个产物")}</div>
<div id="viewerMeta" class="viewer-meta">${escapeHtml(state.selectedArtifact?.href || "这里会显示 JSON、文本、HTML 报告、截图和其他日志的预览。")}</div>
</div>
<div class="detail-actions">
<a id="viewerOpen" class="button button-secondary" href="${escapeHtml(state.selectedArtifact?.href || run.dashboard_refs.report_html)}" target="_blank" rel="noreferrer">${icon("link")}<span>打开产物</span></a>
<button id="viewerRefresh" class="button button-secondary" type="button">${icon("refresh")}<span>刷新预览</span></button>
</div>
</div>
<div id="viewerFrame" class="viewer-frame"><pre>选择报告、日志、截图、JSON 或 HTML 产物后,会在这里直接预览。</pre></div>
</div>
`)}
${renderPanel("sources", "来源与修复主题", `${escapeHtml((advisory.secondary_source_urls || []).length + (advisory.official_source_url ? 1 : 0))} 条链接`, "sources", `
<div class="tag-row">
${(advisory.aliases || []).map((alias) => `<span class="tag">${escapeHtml(alias)}</span>`).join("")}
${(advisory.secure_code_topics || []).map((topic) => `<a class="tag" href="/docs/secure-code-index.html" target="_blank" rel="noreferrer">${escapeHtml(topic)}</a>`).join("")}
</div>
<div class="source-links">${sourceLinks}</div>
`)}
${renderArchitecturePanel()}
${renderPanel("run_json", "运行 JSON", "原始数据", "json", rawRunContent)}
${renderPanel("advisory_json", "漏洞条目 JSON", "原始数据", "json", rawAdvisoryContent)}
${renderPanel("profile_json", "复现档案 JSON", "原始数据", "json", rawProfileContent)}
`;
}
function renderOverviewWorkspace() {
const runs = recentRuns(6);
const systems = filteredSystems().slice(0, 12);
return `
<div class="workspace-stack">
<section class="detail-hero">
<div class="detail-topline">
<span class="status-pill status-default">总览</span>
<div class="tag-row">
<span class="tag">分类路由已启用</span>
<span class="tag">长下拉已移除</span>
<span class="tag">URL 按板块分类</span>
</div>
</div>
<h2 class="detail-title">按板块浏览当前工作台</h2>
<div class="detail-subtitle">根入口保留为概览页,同时新增运行、系统、架构、文档和数据的独立 URL。顶部菜单负责分类切换,搜索与筛选会同步到地址栏。</div>
</section>
${renderPanel("overview_runs", "最新运行", `${escapeHtml(runs.length)}`, "queue", renderRunList(runs, "暂无运行数据。"))}
${renderPanel("overview_systems", "系统覆盖概览", `${escapeHtml(systems.length)} 个系统`, "systems", `<div class="system-grid">${renderSystemCards(systems)}</div>`)}
${renderArchitecturePanel()}
${renderPanel("overview_docs", "文档与数据入口", `${escapeHtml(DOC_HUB_ITEMS.length + DATA_HUB_ITEMS.length)} 个入口`, "docs", `${renderHubCards(DOC_HUB_ITEMS.slice(0, 4).concat(DATA_HUB_ITEMS.slice(0, 4)))}`)}
</div>
`;
}
function renderSystemsWorkspace() {
const items = filteredSystems();
return `
<div class="workspace-stack">
<section class="detail-hero">
<div class="detail-topline">
<span class="status-pill status-default">系统分组</span>
<div class="tag-row">
<span class="tag">共 ${escapeHtml(items.length)} 个系统</span>
${state.filters.category ? `<span class="tag">${escapeHtml(formatCategory(state.filters.category))}</span>` : ""}
${state.filters.system ? `<span class="tag">已锁定 ${escapeHtml(state.filters.system)}</span>` : ""}
</div>
</div>
<h2 class="detail-title">按系统与板块查看覆盖</h2>
<div class="detail-subtitle">顶部只保留板块 chips,不再使用过长下拉。若要精确到单系统,可在卡片上点“锁定系统”或直接进入该系统的运行中心。</div>
</section>
${renderPanel("systems_grid", "系统覆盖列表", `${escapeHtml(items.length)} 个系统`, "systems", `<div class="system-grid">${renderSystemCards(items)}</div>`)}
</div>
`;
}
function renderArchitectureWorkspace() {
return `
<div class="workspace-stack">
<section class="detail-hero">
<div class="detail-topline">
<span class="status-pill status-default">架构库</span>
<div class="tag-row">
<span class="tag">控制面</span>
<span class="tag">数据层</span>
<span class="tag">授权边界</span>
<span class="tag">系统覆盖</span>
</div>
</div>
<h2 class="detail-title">完整架构树与本地入口</h2>
<div class="detail-subtitle">这里是当前仓库的结构化真值视图。可以折叠查看任意层级信息,并跳转到对应的本地路由、文档镜像或 JSON。</div>
</section>
${renderArchitecturePanel()}
</div>
`;
}
function renderDocsWorkspace() {
return `
<div class="workspace-stack">
<section class="detail-hero">
<div class="detail-topline">
<span class="status-pill status-default">文档中心</span>
<div class="tag-row">
<span class="tag">项目文档</span>
<span class="tag">设计文档</span>
<span class="tag">镜像页</span>
</div>
</div>
<h2 class="detail-title">文档入口按板块集中</h2>
<div class="detail-subtitle">不再把所有入口混在首页链接堆里。这里按说明、设计、真值镜像和 secure-code 索引集中展示。</div>
</section>
${renderPanel("docs_hub", "文档与镜像页", `${escapeHtml(DOC_HUB_ITEMS.length)} 个入口`, "docs", renderHubCards(DOC_HUB_ITEMS))}
</div>
`;
}
function renderDataWorkspace() {
return `
<div class="workspace-stack">
<section class="detail-hero">
<div class="detail-topline">
<span class="status-pill status-default">数据中心</span>
<div class="tag-row">
<span class="tag">JSON 真值</span>
<span class="tag">生成产物</span>
<span class="tag">本地直链</span>
</div>
</div>
<h2 class="detail-title">数据入口按类型集中</h2>
<div class="detail-subtitle">summary、runs、systems、advisories、profiles、architecture 已单独归入数据中心,避免和文档、运行详情混在一个地址里。</div>
</section>
${renderPanel("data_hub", "JSON 与生成数据", `${escapeHtml(DATA_HUB_ITEMS.length)} 个入口`, "json", renderHubCards(DATA_HUB_ITEMS))}
</div>
`;
}
function progressSegments(progress) {
const order = [
["completed", "已完成", "progress-completed"],
["blocked", "已阻塞", "progress-blocked"],
["failed", "失败", "progress-failed"],
["skipped", "已跳过", "progress-skipped"],
["planned", "已规划", "progress-planned"],
["other", "其他", "progress-other"]
];
const total = order.reduce((sum, [key]) => sum + Number(progress?.[key] || 0), 0);
if (!total) {
return {
bar: `<div class="progress-segment progress-other" style="width:100%"></div>`,
legend: `<span class="tag"><span class="swatch progress-other"></span>暂无进度</span>`
};
}
const bar = order
.filter(([key]) => Number(progress?.[key] || 0) > 0)
.map(([key, _label, className]) => {
const pct = Math.max((Number(progress[key] || 0) / total) * 100, 4);
return `<span class="progress-segment ${className}" style="width:${pct}%"></span>`;
})
.join("");
const legend = order
.filter(([key]) => Number(progress?.[key] || 0) > 0)
.map(([key, label, className]) => `<span class="tag"><span class="swatch ${className}"></span>${escapeHtml(label)} ${escapeHtml(progress[key] || 0)}</span>`)
.join("");
return { bar, legend };
}
function timelineTone(status) {
if (status === "completed" || status === "verified-real" || status === "verified-synthetic") return "timeline-success";
if (String(status || "").startsWith("blocked") || status === "failed") return "timeline-blocked";
if (status === "planned") return "timeline-pending";
return "timeline-neutral";
}
function renderWorkspace() {
const workspace = $("detailWorkspace");
let html = "";
if (state.routeSection === "runs") html = renderRunWorkspace();
else if (state.routeSection === "systems") html = renderSystemsWorkspace();
else if (state.routeSection === "architecture") html = renderArchitectureWorkspace();
else if (state.routeSection === "docs") html = renderDocsWorkspace();
else if (state.routeSection === "data") html = renderDataWorkspace();
else html = renderOverviewWorkspace();
workspace.innerHTML = html;
}
function renderAll() {
renderMetrics();
renderSectionNav();
renderTopMenus();
renderSidebar();
renderWorkspace();
updateUrl();
}
function setFilter(key, value) {
if (!Object.prototype.hasOwnProperty.call(state.filters, key)) return;
state.filters[key] = value || "";
if (key !== "search") {
if (state.routeSection === "runs" && state.selectedRunId && !filteredRuns().some((item) => item.run_id === state.selectedRunId)) {
state.selectedRunId = filteredRuns()[0]?.run_id || null;
}
}
renderAll();
}
function clearFilters() {
state.filters = {
search: "",
status: "",
category: "",
family: "",
system: ""
};
state.selectedRunId = state.routeSection === "runs" ? filteredRuns()[0]?.run_id || null : state.selectedRunId;
renderAll();
}
function attachGlobalEvents() {
document.addEventListener("click", (event) => {
const toggle = event.target.closest("[data-panel-toggle]");
if (toggle) {
const key = toggle.dataset.panelToggle;
state.panels[key] = !(state.panels[key] !== false);
const panel = document.querySelector(`[data-panel="${key}"]`);
if (panel) panel.classList.toggle("is-collapsed", state.panels[key] === false);
return;
}
const refreshButton = event.target.closest("#refreshDashboard");
if (refreshButton) {
loadData(false);
return;
}
const viewerRefresh = event.target.closest("#viewerRefresh");
if (viewerRefresh && state.selectedArtifact) {
openArtifact(state.selectedArtifact.href, state.selectedArtifact.label, state.selectedArtifact.kind);
return;
}
const runButton = event.target.closest("[data-run-id]");
if (runButton) {
const runId = runButton.dataset.runId;
if (state.routeSection !== "runs") {
navigateToSection("runs", { run: runId });
return;
}
state.selectedRunId = runId;
renderAll();
return;
}
const filterButton = event.target.closest("[data-filter-key]");
if (filterButton) {
setFilter(filterButton.dataset.filterKey, filterButton.dataset.filterValue || "");
return;
}
const clearButton = event.target.closest("[data-clear-filters]");
if (clearButton) {
clearFilters();
return;
}
const artifactButton = event.target.closest("[data-artifact]");
if (artifactButton) {
openArtifact(artifactButton.dataset.href, artifactButton.dataset.label, artifactButton.dataset.kind);
}
});
document.addEventListener("input", (event) => {
if (event.target.id === "searchInput") {
state.filters.search = String(event.target.value || "").trim().toLowerCase();
renderAll();
}
if (event.target.id === "autoRefresh") {
state.autoRefresh = Boolean(event.target.checked);
startRefreshLoop();
}
});
}
function startRefreshLoop() {
if (state.refreshHandle) {
clearInterval(state.refreshHandle);
state.refreshHandle = null;
}
if (!state.autoRefresh) return;
state.refreshHandle = setInterval(() => loadData(true), state.refreshMs);
}
async function loadData(preserveSelection = true) {
const previousRunId = state.selectedRunId;
renderSyncState("loading", "刷新中", `本地时间 ${new Date().toLocaleTimeString("zh-CN", { hour12: false })}`);
try {
const [summary, runs, systems, advisories, profiles, architecture] = await Promise.all([
fetchJson("/summary.json"),
fetchJson("/runs.json"),
fetchJson("/systems.json"),
fetchJson("/advisories.json"),
fetchJson("/profiles.json"),
fetchJson("/architecture.json")
]);
state.summary = summary;
state.runs = runs;
state.systems = systems;
state.advisories = advisories;
state.profiles = profiles;
state.architecture = architecture;
const filtered = filteredRuns();
const candidate = preserveSelection ? (state.selectedRunId || previousRunId) : state.selectedRunId;
if (candidate && filtered.some((item) => item.run_id === candidate)) {
state.selectedRunId = candidate;
} else {
state.selectedRunId = filtered[0]?.run_id || null;
}
renderAll();
renderSyncState("live", "实时同步", `最近生成 ${formatDateTime(summary.generated_at || new Date().toISOString())}`);
} catch (error) {
$("sidebar").innerHTML = `<section class="sidebar-section"><div class="empty-state">工作台加载失败:${escapeHtml(error.message)}</div></section>`;
$("detailWorkspace").innerHTML = `<div class="workspace-empty"><h2>加载失败</h2><p class="empty-copy">${escapeHtml(error.message)}</p></div>`;
renderSyncState("error", "加载失败", error.message);
}
}
async function init() {
applyUrlState();
attachGlobalEvents();
await loadData(false);
startRefreshLoop();
}
document.addEventListener("DOMContentLoaded", init);