@
feat(圆桌): Step3 三产物并行 + 大屏多页模式 + 后台挂起查看恢复流程 后台挂起 Step3: - engine 总结报告/结果绘制/大屏数据 asyncio.gather 三流并行,故障隔离 - request.state 回归修复(进程内虚拟 request 补 state),恢复后台报告 - ROUNDTABLE_JOB_GATEWAY 默认 inprocess;产物自愈重试(截断/缺失纠偏) - 大屏后端只产 report-json(dashboardJson),前端按当前主题渲染 结果绘制大屏多页模式(模式二): - report-template 模板渲染(report-json→大屏HTML),零截断、主题跟随 - 与模式一同款交互(流式+沙箱+可修改);沙箱新窗口打开按钮 最终方案展示:左侧席位栏+总控头像、交付/文件合并、收展动画、内联沙箱 后台挂起查看=恢复实时流程: - handleLoadDraft 返回 Promise,await hydrate 后订阅 streamJob SSE 跟随 - saveDraftNow 强制存(发起前+查看前各一次)防丢 第二步优化:总控判断串/并行(并行单列可写)、席位上下文+交付模板、 peerDeliveries、失败重试、共识标记、流程图小窗(缩放/拖动/并行批) Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> @
This commit is contained in:
1 parent
a7596001c5
commit
d5f319d9cb
51 files changed
+5016
-1186
No files matched your search
@@ -11,6 +11,7 @@ import test from "node:test";
|
||||
import {
|
||||
detectFlowIntent,
|
||||
extractFlowGraph,
|
||||
hasFlowFence,
|
||||
layoutFlowGraph,
|
||||
stripFlowFence,
|
||||
} from "./flow-graph";
|
||||
@@ -128,6 +129,16 @@ test("detectFlowIntent:普通措辞不误触发", () => {
|
||||
assert.equal(detectFlowIntent(undefined), false);
|
||||
});
|
||||
|
||||
test("hasFlowFence:判定回复主产物是否为流程图(流式半截也算)", () => {
|
||||
assert.ok(hasFlowFence(FULL)); // 完整闭合块
|
||||
assert.ok(hasFlowFence('说明文字\n```flow-json\n{"nodes":[')); // 流式半截、未闭合
|
||||
assert.equal(hasFlowFence("纯文字报告正文,没有流程图"), false);
|
||||
assert.equal(hasFlowFence("```json\n{}\n```"), false); // 普通 json 块不算
|
||||
assert.equal(hasFlowFence(""), false);
|
||||
assert.equal(hasFlowFence(null), false);
|
||||
assert.equal(hasFlowFence(undefined), false);
|
||||
});
|
||||
|
||||
test("layoutFlowGraph:环不死循环", () => {
|
||||
const text = [
|
||||
"```flow-json",
|
||||
|
||||
@@ -236,6 +236,11 @@ export function detectFlowIntent(text: string | null | undefined): boolean {
|
||||
return FLOW_INTENT_PATTERNS.some((p) => lower.includes(p));
|
||||
}
|
||||
|
||||
/** 文本里是否带 flow-json 代码块(判定某轮回复的主产物是不是流程图)。 */
|
||||
export function hasFlowFence(text: string | null | undefined): boolean {
|
||||
return !!text && text.includes(FLOW_FENCE_OPEN);
|
||||
}
|
||||
|
||||
/**
|
||||
* 把回复里的 flow-json 块替换成一句人话(气泡里不展示生 JSON)。
|
||||
* 块未闭合(流式中)→「正在输出」措辞;已闭合 → 引导去看流程图画布。
|
||||
|
||||
@@ -0,0 +1,129 @@
|
||||
/**
|
||||
* 后台作业 → Step2 实时画面映射(2026-06-13「查看=恢复流程」)。
|
||||
*
|
||||
* 用户点「查看」一个**运行中**的后台作业时:加载草稿后订阅 `streamJob` SSE,
|
||||
* 把每帧 `RoundtableJob.dialogues`(执行器落库的中性对话记录)映射成前端
|
||||
* `Step2Dialogue` + `seatStubMessages`,灌进 useStep2Orchestration ——
|
||||
* 第二步消息列表像本地编排一样**实时长出**新气泡/步骤卡,而不是静态聊天记录。
|
||||
*
|
||||
* 映射规则与后端 `roundtable_job_executor._to_step2_dialogue` / `_seat_stub_messages`
|
||||
* 逐字段对齐(id/steps/threadId/time/stub 约定一致),保证 SSE 实时帧与作业终态
|
||||
* 写进草稿的 run 形状无缝衔接(终态重载草稿不会跳变)。
|
||||
*/
|
||||
import type {
|
||||
Step2Dialogue,
|
||||
StubAiMessage,
|
||||
} from "@/roundtable-planning/hooks/useStep2Orchestration";
|
||||
import type { JobDialogue, RoundtableJob } from "@/roundtable-planning/lib/job-types";
|
||||
import { getAvatarTypeFor } from "@/roundtable-planning/lib/roundtable-constants";
|
||||
|
||||
/** 工具步骤卡回退文案(对齐执行器 _STEP_LABEL;前端 getStepDisplay 主要按 key 推导)。 */
|
||||
const STEP_LABEL: Record<string, string> = {
|
||||
agent_orchestration: "派活给子智能体",
|
||||
write_file: "写入文件",
|
||||
str_replace: "写入文件",
|
||||
read_file: "读取文件",
|
||||
ls: "列出文件夹",
|
||||
bash: "执行命令",
|
||||
web_search: "搜索相关信息",
|
||||
ask_clarification: "需要你的协助",
|
||||
present_files: "展示文件",
|
||||
};
|
||||
|
||||
function stepsFromToolCalls(
|
||||
toolCalls: NonNullable<JobDialogue["toolCalls"]>,
|
||||
dialogueId: number,
|
||||
ts: string,
|
||||
): NonNullable<Step2Dialogue["steps"]> {
|
||||
const steps: NonNullable<Step2Dialogue["steps"]> = [];
|
||||
toolCalls.forEach((tc, i) => {
|
||||
const name = tc?.name ?? "";
|
||||
if (!name) return;
|
||||
steps.push({
|
||||
id: `${dialogueId}-${i}`,
|
||||
key: `tool_calling:${name}`,
|
||||
label: STEP_LABEL[name] ?? `使用 “${name}” 工具`,
|
||||
ts,
|
||||
args: (tc.args ?? {}) as Record<string, unknown>,
|
||||
});
|
||||
});
|
||||
return steps;
|
||||
}
|
||||
|
||||
function toStep2Dialogue(d: JobDialogue, idxByAgent: Map<string, number>): Step2Dialogue {
|
||||
const time = d.time ?? "";
|
||||
const base: Step2Dialogue = {
|
||||
id: d.id,
|
||||
sender: "",
|
||||
avatarType: "blue",
|
||||
content: d.content ?? "",
|
||||
time,
|
||||
confidence: "",
|
||||
streaming: false,
|
||||
steps: stepsFromToolCalls(d.toolCalls ?? [], d.id, time),
|
||||
};
|
||||
if (d.threadId) base.agentThreadId = d.threadId;
|
||||
if (d.role === "leader") {
|
||||
return { ...base, sender: "总控协调", avatarType: "blue", confidence: "派活说明" };
|
||||
}
|
||||
const aid = d.agentId ?? "";
|
||||
return {
|
||||
...base,
|
||||
sender: d.name || aid,
|
||||
avatarType: getAvatarTypeFor(aid, idxByAgent.get(aid.toLowerCase()) ?? 0),
|
||||
confidence: "子智能体交付",
|
||||
};
|
||||
}
|
||||
|
||||
/** 从各对话的 write_file 重建 seatStubMessages(同 thread 跨轮按 path 去重、后写覆盖)。 */
|
||||
function seatStubsFromDialogues(dialogues: JobDialogue[]): Record<string, StubAiMessage[]> {
|
||||
const byTid = new Map<string, Map<string, NonNullable<JobDialogue["toolCalls"]>[number]>>();
|
||||
for (const d of dialogues) {
|
||||
const tid = d.threadId;
|
||||
if (!tid) continue;
|
||||
for (const tc of d.toolCalls ?? []) {
|
||||
if (tc?.name !== "write_file") continue;
|
||||
const path = String((tc.args as { path?: unknown } | undefined)?.path ?? "");
|
||||
let m = byTid.get(tid);
|
||||
if (!m) {
|
||||
m = new Map();
|
||||
byTid.set(tid, m);
|
||||
}
|
||||
m.set(path, tc); // 后写覆盖
|
||||
}
|
||||
}
|
||||
const out: Record<string, StubAiMessage[]> = {};
|
||||
for (const [tid, byPath] of byTid) {
|
||||
const toolCalls = Array.from(byPath.values()).map((tc, i) => ({
|
||||
id: `tc-${tid}-${i}`,
|
||||
name: "write_file",
|
||||
args: (tc.args ?? {}) as Record<string, unknown>,
|
||||
}));
|
||||
out[tid] = [{ id: `roundtable-stub-${tid}`, type: "ai", content: "", tool_calls: toolCalls }];
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
export interface LiveJobFrame {
|
||||
dialogues: Step2Dialogue[];
|
||||
seatStubMessages: Record<string, StubAiMessage[]>;
|
||||
consensusPercentage: number;
|
||||
hasConsensus: boolean;
|
||||
lastLeaderContent: string;
|
||||
}
|
||||
|
||||
/** 把一帧作业快照映射成 Step2 实时画面数据。 */
|
||||
export function mapJobToLiveStep2(job: RoundtableJob): LiveJobFrame {
|
||||
const idxByAgent = new Map<string, number>();
|
||||
job.dispatchChain.forEach((n, i) => idxByAgent.set(n.agentId.toLowerCase(), i));
|
||||
const dialogues = job.dialogues.map((d) => toStep2Dialogue(d, idxByAgent));
|
||||
const lastLeader =
|
||||
[...job.dialogues].reverse().find((d) => d.role === "leader")?.content ?? "";
|
||||
return {
|
||||
dialogues,
|
||||
seatStubMessages: seatStubsFromDialogues(job.dialogues),
|
||||
consensusPercentage: job.consensusPercentage,
|
||||
hasConsensus: job.status === "done",
|
||||
lastLeaderContent: lastLeader,
|
||||
};
|
||||
}
|
||||
@@ -25,8 +25,9 @@ export type JobPhase =
|
||||
| "leader_thinking" // 总控在决策派活
|
||||
| "dispatching" // 正在顺序派活给席位(配合 activeAgentId)
|
||||
| "consensus" // 共识达成(dispatched=[])
|
||||
| "report_drawing" // Step3 报告绘制中
|
||||
| "report_done"; // 绘制完成
|
||||
| "summary_writing" // Step3 方案总结报告撰写中(roundtable-summary 写 md)
|
||||
| "report_drawing" // Step3 结果绘制中(roundtable-report 画 HTML)
|
||||
| "report_done"; // Step3 完成
|
||||
|
||||
/** 派活链路单节点状态(驱动颜色 / 动画)。 */
|
||||
export type ChainNodeState = "pending" | "active" | "done";
|
||||
@@ -55,6 +56,12 @@ export interface JobDialogue {
|
||||
name: string;
|
||||
content: string;
|
||||
cycle: number;
|
||||
/** 本轮工具调用({name, args, id})—— 映射成前端步骤卡 / write_file stub。 */
|
||||
toolCalls?: Array<{ name: string; args?: Record<string, unknown>; id?: string }>;
|
||||
/** 该气泡对应的 leader/seat 线程 id(点开产物用)。 */
|
||||
threadId?: string | null;
|
||||
/** 气泡时间戳(HH:MM:SS,后端创建时盖章)。 */
|
||||
time?: string;
|
||||
}
|
||||
|
||||
/** 一条后台作业的完整快照(§2.5)——对齐后端 `RoundtableJobResponse`(camelCase)。 */
|
||||
@@ -75,8 +82,23 @@ export interface RoundtableJob {
|
||||
error: string | null;
|
||||
/** 研讨对话记录(leader 说明 + 各席位交付),跑完 / 进行中都可看真实内容。 */
|
||||
dialogues: JobDialogue[];
|
||||
/** Step3 报告快照(done 时有):{ html, generatedAt, model, summary }。 */
|
||||
step3: { html: string; generatedAt?: string; model?: string; summary?: string } | null;
|
||||
/** Step3 快照(done 时有):结果绘制 { html, … } + 嵌套的方案总结报告 summaryReport。 */
|
||||
step3: {
|
||||
html?: string;
|
||||
generatedAt?: string;
|
||||
model?: string;
|
||||
summary?: string;
|
||||
/** 方案总结报告(roundtable-summary 的 md)——与草稿 DraftStep3SummarySnapshot 同形状。 */
|
||||
summaryReport?: {
|
||||
md: string;
|
||||
threadId?: string;
|
||||
generatedAt?: string;
|
||||
model?: string;
|
||||
closing?: string;
|
||||
} | null;
|
||||
/** 大屏多页(模式二)的 report-json 数据字符串(前端按当前主题渲染)。 */
|
||||
dashboardJson?: string | null;
|
||||
} | null;
|
||||
createdAt: string | null;
|
||||
updatedAt: string | null;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,159 @@
|
||||
/**
|
||||
* report-template.ts 纯函数单测(大屏多页模式的契约层)。
|
||||
* 运行方式(项目无 vitest,对齐 flow-graph.test.ts):
|
||||
* npx esbuild src/roundtable-planning/lib/report-template.test.ts --bundle --format=esm \
|
||||
* --platform=node --outfile=.tmp-tests/report-template.test.mjs
|
||||
* node --test .tmp-tests/report-template.test.mjs
|
||||
*/
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
|
||||
import {
|
||||
buildDashboardPrompt,
|
||||
extractReportData,
|
||||
isDashboardHtml,
|
||||
renderDashboardHtml,
|
||||
RT_DASHBOARD_MARKER,
|
||||
stripReportFence,
|
||||
} from "./report-template";
|
||||
|
||||
const SAMPLE = [
|
||||
"下面是大屏数据。",
|
||||
"```report-json",
|
||||
JSON.stringify({
|
||||
title: "智能机房选址方案大屏",
|
||||
subtitle: "三地候选 · 综合评审",
|
||||
kpis: [
|
||||
{ label: "总投资", value: "1.2", unit: "亿元", trend: "up" },
|
||||
{ label: "工期", value: "14", unit: "个月" },
|
||||
],
|
||||
consensus: { headline: "推荐 B 地块方案", points: ["供电冗余最高", "扩容空间充足"] },
|
||||
charts: [
|
||||
{ type: "bar", title: "候选地块评分", items: [{ label: "A", value: 72 }, { label: "B", value: 89 }] },
|
||||
{ type: "donut", title: "投资构成", items: [{ label: "土建", value: 40 }, { label: "设备", value: 60 }] },
|
||||
],
|
||||
timeline: [{ label: "阶段一", desc: "勘察与立项" }],
|
||||
seats: [
|
||||
{ id: "seat-1", name: "情报收集", summary: "完成三地基础数据采集", sections: [{ heading: "数据来源", bullets: ["政务公开", "实地走访"] }], metrics: [{ label: "覆盖率", value: 92 }], risks: [], dependsOn: [] },
|
||||
{ id: "seat-2", name: "方案设计", summary: "B 地块双回路供电方案", sections: [], metrics: [], risks: [{ label: "供电瓶颈", level: "high" }], dependsOn: ["seat-1"] },
|
||||
],
|
||||
}),
|
||||
"```",
|
||||
].join("\n");
|
||||
|
||||
test("extractReportData:完整块解析 + 字段归一化", () => {
|
||||
const d = extractReportData(SAMPLE)!;
|
||||
assert.equal(d.title, "智能机房选址方案大屏");
|
||||
assert.equal(d.kpis.length, 2);
|
||||
assert.equal(d.consensus.headline, "推荐 B 地块方案");
|
||||
assert.equal(d.charts.length, 2);
|
||||
assert.equal(d.seats.length, 2);
|
||||
assert.deepEqual(d.seats[1].dependsOn, ["seat-1"]);
|
||||
});
|
||||
|
||||
test("extractReportData:dependsOn 只保留真实存在的席位 id(剔除模型编造/自引用)", () => {
|
||||
const text = [
|
||||
"```report-json",
|
||||
JSON.stringify({
|
||||
title: "t",
|
||||
seats: [
|
||||
{ id: "s1", name: "甲", dependsOn: ["s1", "s2", "ghost"] },
|
||||
{ id: "s2", name: "乙", dependsOn: [] },
|
||||
],
|
||||
}),
|
||||
"```",
|
||||
].join("\n");
|
||||
const d = extractReportData(text)!;
|
||||
assert.deepEqual(d.seats[0].dependsOn, ["s2"]);
|
||||
});
|
||||
|
||||
test("extractReportData:无 fence / 坏 JSON / 空数据返回 null", () => {
|
||||
assert.equal(extractReportData("没有数据块"), null);
|
||||
assert.equal(extractReportData("```report-json\n{broken\n```"), null);
|
||||
assert.equal(extractReportData("```report-json\n{}\n```"), null);
|
||||
assert.equal(extractReportData(null), null);
|
||||
});
|
||||
|
||||
test("renderDashboardHtml:完整文档 + marker + 总览/席位多页 + :target 导航", () => {
|
||||
const d = extractReportData(SAMPLE)!;
|
||||
const html = renderDashboardHtml(d, { generatedAt: "2026-06-13 10:00" });
|
||||
assert.ok(html.startsWith("<!doctype html>"));
|
||||
assert.ok(html.includes(RT_DASHBOARD_MARKER));
|
||||
assert.ok(html.trimEnd().endsWith("</html>"));
|
||||
assert.ok(isDashboardHtml(html));
|
||||
// 多页结构:总览 + 每席位一页
|
||||
assert.ok(html.includes('id="overview"'));
|
||||
assert.ok(html.includes('id="seat-1"'));
|
||||
assert.ok(html.includes('id="seat-2"'));
|
||||
// 纯 CSS :target 导航(零 JS:无 allow-scripts 沙箱也能切页)
|
||||
assert.ok(html.includes(".page:target"));
|
||||
assert.ok(!html.includes("<script"));
|
||||
// 席位卡片跳转 + 依赖互相跳转(方案设计 依赖→ 情报收集)
|
||||
assert.ok(html.includes('href="#seat-2"'));
|
||||
assert.ok(html.includes('class="dep" href="#seat-1"'));
|
||||
// 反向「被依赖」chip(情报收集页里出现 方案设计 ← 承接)
|
||||
assert.ok(html.includes("承接本席位"));
|
||||
// 共识详情纯 CSS 弹窗
|
||||
assert.ok(html.includes('id="consensus-modal"'));
|
||||
// 图表 SVG 由模板生成
|
||||
assert.ok(html.includes("<svg"));
|
||||
});
|
||||
|
||||
test("renderDashboardHtml:主题跟随 —— dark=深蓝规范 / light=浅红规范", () => {
|
||||
const d = extractReportData(SAMPLE)!;
|
||||
const dark = renderDashboardHtml(d, { theme: "dark" });
|
||||
// 深蓝规范:页面 #0C1836 / 卡片 #122347 / 主色 #1677FF(tokens.css §1)
|
||||
assert.ok(dark.includes("#0C1836"));
|
||||
assert.ok(dark.includes("#122347"));
|
||||
assert.ok(dark.includes("#1677FF"));
|
||||
const light = renderDashboardHtml(d, { theme: "light" });
|
||||
// 浅红规范:页面 #FAFAFA / 容器 #FFFFFF / 主色 #F5222D(§1 色彩)
|
||||
assert.ok(light.includes("#FAFAFA"));
|
||||
assert.ok(light.includes("#F5222D"));
|
||||
assert.ok(!light.includes("#0C1836"));
|
||||
// 缺省 = dark(向后兼容)
|
||||
const def = renderDashboardHtml(d);
|
||||
assert.ok(def.includes("#0C1836"));
|
||||
});
|
||||
|
||||
test("renderDashboardHtml:模型文本全部 HTML 转义(防注入/破版)", () => {
|
||||
const text = [
|
||||
"```report-json",
|
||||
JSON.stringify({
|
||||
title: '<img src=x onerror=alert(1)>',
|
||||
seats: [{ id: "s1", name: "甲<b>", summary: 'a"b<c>', dependsOn: [] }],
|
||||
consensus: { headline: "<script>bad()</script>", points: [] },
|
||||
}),
|
||||
"```",
|
||||
].join("\n");
|
||||
const d = extractReportData(text)!;
|
||||
const html = renderDashboardHtml(d);
|
||||
assert.ok(!html.includes("<img src=x"));
|
||||
assert.ok(!html.includes("<script>bad"));
|
||||
assert.ok(html.includes("<script>bad()</script>"));
|
||||
});
|
||||
|
||||
test("stripReportFence:闭合块替换为引导语;未闭合(流式中)用「正在输出」措辞", () => {
|
||||
const done = stripReportFence(SAMPLE, false);
|
||||
assert.ok(done.includes("已生成大屏数据"));
|
||||
assert.ok(!done.includes("```report-json"));
|
||||
const streaming = stripReportFence('说明\n```report-json\n{"title":', true);
|
||||
assert.ok(streaming.includes("正在输出大屏结构化数据"));
|
||||
assert.ok(!streaming.includes("```report-json"));
|
||||
// 无 fence 原样返回
|
||||
assert.equal(stripReportFence("普通文字", false), "普通文字");
|
||||
});
|
||||
|
||||
test("buildDashboardPrompt:禁工具声明 + 原料齐全 + 契约说明", () => {
|
||||
const prompt = buildDashboardPrompt({
|
||||
intentText: "选址决策",
|
||||
seatDeliveries: [{ sender: "情报收集", content: "三地数据" }],
|
||||
consensusText: "推荐 B 地块",
|
||||
});
|
||||
assert.ok(prompt.includes("不要调用任何工具"));
|
||||
assert.ok(prompt.includes("选址决策"));
|
||||
assert.ok(prompt.includes("情报收集") && prompt.includes("三地数据"));
|
||||
assert.ok(prompt.includes("推荐 B 地块"));
|
||||
assert.ok(prompt.includes("```report-json"));
|
||||
assert.ok(prompt.includes("dependsOn"));
|
||||
});
|
||||
@@ -0,0 +1,722 @@
|
||||
/**
|
||||
* Step3「结果绘制 · 大屏多页模式(模式二)」—— report-json 契约 + 模板渲染器。
|
||||
*
|
||||
* 设计动机(2026-06-13):模式一让模型从零写整份 50KB+ 自包含 HTML,慢(1-3 分钟)
|
||||
* 且有超长截断风险。模式二把 HTML 骨架/样式/图表**全部预置在本模板里**,模型只输出
|
||||
* 1-2KB 的结构化 ```report-json 数据(与 Step3 总结报告的 flow-json 同一套路),
|
||||
* 前端代码确定性地渲染成完整大屏 HTML —— 快一个数量级、零截断、风格稳定。
|
||||
*
|
||||
* ## report-json 契约(模型输出)
|
||||
* ```report-json
|
||||
* {"title":"…","subtitle":"…",
|
||||
* "kpis":[{"label":"总投资","value":"1.2","unit":"亿元","trend":"up"}],
|
||||
* "consensus":{"headline":"一句话最终结论","points":["…"]},
|
||||
* "charts":[{"type":"bar|donut|radar","title":"…","items":[{"label":"…","value":30}]}],
|
||||
* "timeline":[{"label":"阶段一","desc":"…"}],
|
||||
* "seats":[{"id":"seat-1","name":"方案设计","summary":"一两句结论",
|
||||
* "sections":[{"heading":"…","bullets":["…"]}],
|
||||
* "metrics":[{"label":"可行性","value":86}],
|
||||
* "risks":[{"label":"…","level":"high|mid|low"}],
|
||||
* "dependsOn":["seat-0"]}]}
|
||||
* ```
|
||||
*
|
||||
* ## 生成的页面结构(单文件 · 零 JS · 离线自包含)
|
||||
* - 大屏展示风:深海军蓝渐变底 + 网格底纹 + 青色霓虹描边玻璃卡片 + 四角装饰括号;
|
||||
* - **总览页**(KPI 带 + 共识结论 + 总览图表 + 席位卡片矩阵 + 执行时间线)
|
||||
* + **每席位一页**(该席位交付的结构化展示 + 指标条 + 风险徽标 + 依赖面板);
|
||||
* - 导航纯 CSS `:target`:页签/席位卡片/依赖 chips 都是 `#seat-x` 锚点跳转,
|
||||
* `.page:target` 显示目标页、`body:has(.page:target)` 隐藏默认总览 ——
|
||||
* **无 allow-scripts 的沙箱 iframe / 公开分享页都能正常切页**;
|
||||
* - 「弹窗」同样用 :target 纯 CSS overlay(共识详情);
|
||||
* - 席位间依赖(dependsOn)渲染成双向 chips(依赖 → / ← 支撑),点击互相跳转。
|
||||
*
|
||||
* 文件头嵌入 `RT_DASHBOARD_MARKER` 注释,恢复草稿时据此识别「这是模板大屏」。
|
||||
*/
|
||||
|
||||
// ── 契约类型 ─────────────────────────────────────────────────────────────────
|
||||
|
||||
export interface ReportKpi {
|
||||
label: string;
|
||||
value: string;
|
||||
unit?: string;
|
||||
trend?: "up" | "down" | "flat";
|
||||
}
|
||||
|
||||
export interface ReportChartItem {
|
||||
label: string;
|
||||
value: number;
|
||||
}
|
||||
|
||||
export interface ReportChart {
|
||||
type: "bar" | "donut" | "radar";
|
||||
title: string;
|
||||
items: ReportChartItem[];
|
||||
}
|
||||
|
||||
export interface ReportSeatSection {
|
||||
heading: string;
|
||||
bullets: string[];
|
||||
}
|
||||
|
||||
export interface ReportSeatMetric {
|
||||
label: string;
|
||||
/** 0-100。 */
|
||||
value: number;
|
||||
}
|
||||
|
||||
export interface ReportSeatRisk {
|
||||
label: string;
|
||||
level: "high" | "mid" | "low";
|
||||
}
|
||||
|
||||
export interface ReportSeat {
|
||||
id: string;
|
||||
name: string;
|
||||
summary: string;
|
||||
sections: ReportSeatSection[];
|
||||
metrics: ReportSeatMetric[];
|
||||
risks: ReportSeatRisk[];
|
||||
/** 依赖的其它席位 id(产物承接关系),渲染成互相跳转 chips。 */
|
||||
dependsOn: string[];
|
||||
}
|
||||
|
||||
export interface ReportData {
|
||||
title: string;
|
||||
subtitle: string;
|
||||
kpis: ReportKpi[];
|
||||
consensus: { headline: string; points: string[] };
|
||||
charts: ReportChart[];
|
||||
timeline: Array<{ label: string; desc: string }>;
|
||||
seats: ReportSeat[];
|
||||
}
|
||||
|
||||
/** 模板大屏 HTML 的识别标记(恢复草稿时区分模式一/二)。 */
|
||||
export const RT_DASHBOARD_MARKER = "<!-- rt-dashboard-v1 -->";
|
||||
|
||||
/** 大屏 HTML 在沙箱预览里的虚拟产物路径(write_file stub 用,前端渲染、非真实文件)。 */
|
||||
export const DASHBOARD_OUTPUT_PATH = "/mnt/user-data/outputs/方案研讨大屏.html";
|
||||
|
||||
export function isDashboardHtml(html: string | null | undefined): boolean {
|
||||
return !!html && html.includes(RT_DASHBOARD_MARKER);
|
||||
}
|
||||
|
||||
/**
|
||||
* 把回复里的 report-json 块替换成一句人话(气泡里不展示生 JSON,对齐 flow-json 的
|
||||
* stripFlowFence)。块未闭合(流式中)→「正在输出」措辞;已闭合 → 引导看右侧沙箱。
|
||||
*/
|
||||
export function stripReportFence(text: string, streaming: boolean): string {
|
||||
const start = text.lastIndexOf(FENCE);
|
||||
if (start < 0) return text;
|
||||
const after = text.slice(start + FENCE.length);
|
||||
const close = after.indexOf("```");
|
||||
const tail = close >= 0 ? after.slice(close + 3) : "";
|
||||
const placeholder =
|
||||
close < 0 && streaming
|
||||
? "\n\n> 📊 正在输出大屏结构化数据,右侧沙箱稍后自动渲染…"
|
||||
: "\n\n> 📊 已生成大屏数据,右侧沙箱已渲染预览(可继续输入修改要求调整)。";
|
||||
return `${text.slice(0, start).trimEnd()}${placeholder}${tail}`;
|
||||
}
|
||||
|
||||
// ── 解析(容错:取最后一个 report-json 代码块;缺字段给安全默认) ─────────────────
|
||||
|
||||
const FENCE = "```report-json";
|
||||
|
||||
function str(v: unknown, fallback = ""): string {
|
||||
return typeof v === "string" ? v : fallback;
|
||||
}
|
||||
|
||||
function num(v: unknown): number {
|
||||
const n = typeof v === "number" ? v : Number(v);
|
||||
return Number.isFinite(n) ? n : 0;
|
||||
}
|
||||
|
||||
function arr(v: unknown): unknown[] {
|
||||
return Array.isArray(v) ? v : [];
|
||||
}
|
||||
|
||||
/** 从模型回复里提取并归一化 report-json(找不到 / 解析失败 → null)。 */
|
||||
export function extractReportData(text: string | null | undefined): ReportData | null {
|
||||
if (!text) return null;
|
||||
const start = text.lastIndexOf(FENCE);
|
||||
if (start < 0) return null;
|
||||
const after = text.slice(start + FENCE.length);
|
||||
const close = after.indexOf("```");
|
||||
const body = (close >= 0 ? after.slice(0, close) : after).trim();
|
||||
if (!body) return null;
|
||||
return parseReportJson(body);
|
||||
}
|
||||
|
||||
/** 解析裸 JSON 字符串(草稿/后台作业存的 step3.dashboardJson)并归一化。 */
|
||||
export function parseReportJson(jsonStr: string | null | undefined): ReportData | null {
|
||||
if (!jsonStr?.trim()) return null;
|
||||
let raw: unknown;
|
||||
try {
|
||||
raw = JSON.parse(jsonStr);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
return coerceReportData(raw);
|
||||
}
|
||||
|
||||
/** 把已 JSON.parse 的对象归一化成 ReportData(缺字段给安全默认;非法 → null)。 */
|
||||
export function coerceReportData(raw: unknown): ReportData | null {
|
||||
if (!raw || typeof raw !== "object") return null;
|
||||
const o = raw as Record<string, unknown>;
|
||||
|
||||
const seats: ReportSeat[] = arr(o.seats)
|
||||
.map((s, i) => {
|
||||
const so = (s ?? {}) as Record<string, unknown>;
|
||||
const name = str(so.name).trim();
|
||||
if (!name) return null;
|
||||
const id = str(so.id).trim() || `seat-${i + 1}`;
|
||||
return {
|
||||
id,
|
||||
name,
|
||||
summary: str(so.summary),
|
||||
sections: arr(so.sections)
|
||||
.map((sec) => {
|
||||
const co = (sec ?? {}) as Record<string, unknown>;
|
||||
return {
|
||||
heading: str(co.heading),
|
||||
bullets: arr(co.bullets).map((b) => str(b)).filter(Boolean),
|
||||
};
|
||||
})
|
||||
.filter((sec) => sec.heading || sec.bullets.length > 0),
|
||||
metrics: arr(so.metrics)
|
||||
.map((m) => {
|
||||
const mo = (m ?? {}) as Record<string, unknown>;
|
||||
return { label: str(mo.label), value: Math.min(100, Math.max(0, num(mo.value))) };
|
||||
})
|
||||
.filter((m) => m.label),
|
||||
risks: arr(so.risks)
|
||||
.map((r) => {
|
||||
const ro = (r ?? {}) as Record<string, unknown>;
|
||||
const level = str(ro.level);
|
||||
return {
|
||||
label: str(ro.label),
|
||||
level: (level === "high" || level === "mid" || level === "low" ? level : "mid") as
|
||||
| "high"
|
||||
| "mid"
|
||||
| "low",
|
||||
};
|
||||
})
|
||||
.filter((r) => r.label),
|
||||
dependsOn: arr(so.dependsOn).map((d) => str(d).trim()).filter(Boolean),
|
||||
} as ReportSeat;
|
||||
})
|
||||
.filter((s): s is ReportSeat => s !== null);
|
||||
|
||||
// dependsOn 只保留真实存在的席位 id(模型可能编 id)。
|
||||
const idSet = new Set(seats.map((s) => s.id));
|
||||
for (const s of seats) s.dependsOn = s.dependsOn.filter((d) => idSet.has(d) && d !== s.id);
|
||||
|
||||
const consensusRaw = (o.consensus ?? {}) as Record<string, unknown>;
|
||||
const data: ReportData = {
|
||||
title: str(o.title, "方案研讨大屏"),
|
||||
subtitle: str(o.subtitle),
|
||||
kpis: arr(o.kpis)
|
||||
.map((k) => {
|
||||
const ko = (k ?? {}) as Record<string, unknown>;
|
||||
const trend = str(ko.trend);
|
||||
return {
|
||||
label: str(ko.label),
|
||||
value: str(ko.value, String(ko.value ?? "")),
|
||||
unit: str(ko.unit) || undefined,
|
||||
trend: (trend === "up" || trend === "down" || trend === "flat" ? trend : undefined) as
|
||||
| "up"
|
||||
| "down"
|
||||
| "flat"
|
||||
| undefined,
|
||||
};
|
||||
})
|
||||
.filter((k) => k.label && k.value)
|
||||
.slice(0, 6),
|
||||
consensus: {
|
||||
headline: str(consensusRaw.headline),
|
||||
points: arr(consensusRaw.points).map((p) => str(p)).filter(Boolean),
|
||||
},
|
||||
charts: arr(o.charts)
|
||||
.map((c) => {
|
||||
const co = (c ?? {}) as Record<string, unknown>;
|
||||
const type = str(co.type);
|
||||
return {
|
||||
type: (type === "bar" || type === "donut" || type === "radar" ? type : "bar") as
|
||||
| "bar"
|
||||
| "donut"
|
||||
| "radar",
|
||||
title: str(co.title),
|
||||
items: arr(co.items)
|
||||
.map((it) => {
|
||||
const io = (it ?? {}) as Record<string, unknown>;
|
||||
return { label: str(io.label), value: num(io.value) };
|
||||
})
|
||||
.filter((it) => it.label),
|
||||
};
|
||||
})
|
||||
.filter((c) => c.items.length > 0)
|
||||
.slice(0, 3),
|
||||
timeline: arr(o.timeline)
|
||||
.map((t) => {
|
||||
const to = (t ?? {}) as Record<string, unknown>;
|
||||
return { label: str(to.label), desc: str(to.desc) };
|
||||
})
|
||||
.filter((t) => t.label),
|
||||
seats,
|
||||
};
|
||||
if (data.seats.length === 0 && !data.consensus.headline) return null;
|
||||
return data;
|
||||
}
|
||||
|
||||
// ── 模型 prompt(只要 report-json,不调工具、不写文件) ───────────────────────────
|
||||
|
||||
export function buildDashboardPrompt(opts: {
|
||||
intentText: string;
|
||||
seatDeliveries: Array<{ sender: string; content: string }>;
|
||||
consensusText: string;
|
||||
}): string {
|
||||
const parts: string[] = [
|
||||
"【结构化数据模式】本轮**不要调用任何工具、不要写任何文件、不要输出 HTML**。",
|
||||
"请通读以下圆桌研讨成果,把它们提炼成一份大屏展示数据,在回复**最末尾**输出一个完整的 ```report-json 代码块(契约见下),代码块之外只允许一两句简短说明。",
|
||||
"",
|
||||
"# 一、任务意图",
|
||||
(opts.intentText || "").trim() || "(未提供)",
|
||||
"",
|
||||
"# 二、各席位最终交付",
|
||||
];
|
||||
opts.seatDeliveries.forEach((d, i) => {
|
||||
parts.push(`## ${i + 1}. ${d.sender}`);
|
||||
parts.push((d.content || "").trim() || "(无内容)");
|
||||
parts.push("");
|
||||
});
|
||||
parts.push("# 三、总控最终共识结论");
|
||||
parts.push((opts.consensusText || "").trim() || "(未提供)");
|
||||
parts.push("");
|
||||
parts.push(
|
||||
[
|
||||
"```report-json 契约(严格 JSON,全程简体中文):",
|
||||
'{"title":"大屏主标题(≤20字)","subtitle":"一句话定位",',
|
||||
' "kpis":[{"label":"指标名","value":"数值","unit":"单位","trend":"up|down|flat"}], // 3-6 个核心指标,从研讨内容提取或合理估算',
|
||||
' "consensus":{"headline":"一句话最终结论","points":["结论要点,3-6 条"]},',
|
||||
' "charts":[{"type":"bar|donut|radar","title":"图表标题","items":[{"label":"维度","value":数字}]}], // 1-3 个总览图表(风险分布/资源占比/方案评分等),3-6 项/图',
|
||||
' "timeline":[{"label":"阶段名","desc":"一句话说明"}], // 执行路线 3-6 阶段',
|
||||
' "seats":[{"id":"seat-1","name":"席位名(与交付席位一致)","summary":"该席位结论一两句",',
|
||||
' "sections":[{"heading":"小节标题","bullets":["要点,每条≤40字"]}], // 2-4 节,提炼该席位交付',
|
||||
' "metrics":[{"label":"量化指标名","value":0到100}], // 0-3 个',
|
||||
' "risks":[{"label":"风险点","level":"high|mid|low"}], // 0-4 个',
|
||||
' "dependsOn":["它承接哪些席位的产物(席位id)"]}]} // 每个交付席位一项;依据交付内容判断依赖关系',
|
||||
"硬性要求:seats 覆盖**每一个**有交付的席位;id 用 seat-1..seat-N;dependsOn 只引用本清单内的 id;JSON 必须可被 JSON.parse 解析(无注释、无尾逗号)。",
|
||||
].join("\n"),
|
||||
);
|
||||
return parts.join("\n");
|
||||
}
|
||||
|
||||
// ── 主题(2026-06-13):跟随应用当前主题绘制 ─────────────────────────────────────
|
||||
// light = 《浅红色 UI 规范》(docs/浅红色UI规范):白/浅灰大底、#F5222D 品牌红强调、
|
||||
// 卡片 4px 圆角、语义色 成功#189D72/警告#FF9900/错误#F5222D/信息#0079FE;
|
||||
// dark = 《深蓝色 UI 规范》(docs/ui规范-深蓝/tokens.css):页面#0C1836、卡片#122347、
|
||||
// 主色#1677FF、辅色#13C2C2、文字#C5CFE0、语义 成功#52C41A/警告#FAAD14/错误#F5222D。
|
||||
|
||||
export type DashboardTheme = "light" | "dark";
|
||||
|
||||
interface Palette {
|
||||
bgPage: string;
|
||||
bgGradient: string;
|
||||
gridLine: string;
|
||||
card: string;
|
||||
cardBorder: string;
|
||||
cardGlow: string;
|
||||
bracket: string;
|
||||
text: string;
|
||||
textSecondary: string;
|
||||
textStrong: string;
|
||||
heading: string;
|
||||
primary: string;
|
||||
link: string;
|
||||
titleColor: string;
|
||||
navBg: string;
|
||||
trackBg: string;
|
||||
/** 图表 / KPI / 席位强调色序(规范图表色序)。 */
|
||||
accents: string[];
|
||||
risk: { high: string; mid: string; low: string };
|
||||
modalMask: string;
|
||||
}
|
||||
|
||||
const PALETTES: Record<DashboardTheme, Palette> = {
|
||||
dark: {
|
||||
bgPage: "#0C1836",
|
||||
bgGradient:
|
||||
"radial-gradient(1200px 600px at 70% -10%,rgba(22,119,255,.14),transparent),linear-gradient(160deg,#060E24,#0C1836)",
|
||||
gridLine: "rgba(64,150,255,.06)",
|
||||
card: "linear-gradient(160deg,#1A2F5A,#122347)",
|
||||
cardBorder: "rgba(64,150,255,.28)",
|
||||
cardGlow: "0 0 24px rgba(6,14,36,.5) inset,0 4px 18px rgba(6,14,36,.35)",
|
||||
bracket: "#4096FF",
|
||||
text: "#C5CFE0",
|
||||
textSecondary: "#6E88B0",
|
||||
textStrong: "#FFFFFF",
|
||||
heading: "#91CAFF",
|
||||
primary: "#1677FF",
|
||||
link: "#4096FF",
|
||||
titleColor: "linear-gradient(90deg,#91CAFF,#4096FF 45%,#13C2C2)",
|
||||
navBg: "rgba(6,14,36,.88)",
|
||||
trackBg: "rgba(110,136,176,.22)",
|
||||
accents: ["#4096FF", "#13C2C2", "#52C41A", "#FAAD14", "#FF7875", "#69B1FF"],
|
||||
risk: { high: "#F5222D", mid: "#FAAD14", low: "#52C41A" },
|
||||
modalMask: "rgba(6,14,36,.78)",
|
||||
},
|
||||
light: {
|
||||
bgPage: "#FAFAFA",
|
||||
bgGradient:
|
||||
"radial-gradient(1200px 600px at 70% -10%,rgba(245,34,45,.05),transparent),linear-gradient(160deg,#FFFFFF,#FAFAFA)",
|
||||
gridLine: "rgba(245,34,45,.035)",
|
||||
card: "#FFFFFF",
|
||||
cardBorder: "#E8E8E8",
|
||||
cardGlow: "0 2px 8px rgba(0,0,0,.04)",
|
||||
bracket: "#F5222D",
|
||||
text: "#222222",
|
||||
textSecondary: "#575757",
|
||||
textStrong: "#222222",
|
||||
heading: "#A8071A",
|
||||
primary: "#F5222D",
|
||||
link: "#0079FE",
|
||||
titleColor: "linear-gradient(90deg,#F5222D,#CF1322 60%,#A8071A)",
|
||||
navBg: "rgba(255,255,255,.92)",
|
||||
trackBg: "#F0F0F0",
|
||||
accents: ["#F5222D", "#0079FE", "#189D72", "#FF9900", "#45C3F3", "#7F7F7F"],
|
||||
risk: { high: "#F5222D", mid: "#FF9900", low: "#189D72" },
|
||||
modalMask: "rgba(34,34,34,.45)",
|
||||
},
|
||||
};
|
||||
|
||||
// ── 渲染(确定性模板,全部文本 HTML 转义) ────────────────────────────────────────
|
||||
|
||||
function esc(s: string): string {
|
||||
return s
|
||||
.replace(/&/g, "&")
|
||||
.replace(/</g, "<")
|
||||
.replace(/>/g, ">")
|
||||
.replace(/"/g, """);
|
||||
}
|
||||
|
||||
// 渲染期间的当前色板:renderDashboardHtml 开头按主题设置(同步渲染,无并发竞争),
|
||||
// 各 SVG/片段帮助函数直接读,避免把 palette 穿透每个函数签名。
|
||||
let P: Palette = PALETTES.dark;
|
||||
|
||||
function svgBar(chart: ReportChart): string {
|
||||
const items = chart.items.slice(0, 6);
|
||||
const max = Math.max(...items.map((i) => i.value), 1);
|
||||
const W = 300;
|
||||
const rowH = 30;
|
||||
const H = items.length * rowH + 6;
|
||||
const rows = items
|
||||
.map((it, i) => {
|
||||
const w = Math.max(4, (it.value / max) * (W - 110));
|
||||
const y = i * rowH + 6;
|
||||
const color = P.accents[i % P.accents.length];
|
||||
return (
|
||||
`<text x="0" y="${y + 13}" class="cl">${esc(it.label)}</text>` +
|
||||
`<rect x="92" y="${y + 3}" width="${W - 110}" height="14" rx="7" class="ct"/>` +
|
||||
`<rect x="92" y="${y + 3}" width="${w}" height="14" rx="7" fill="${color}" opacity="0.85"/>` +
|
||||
`<text x="${W - 12}" y="${y + 14}" class="cv" text-anchor="end">${esc(String(it.value))}</text>`
|
||||
);
|
||||
})
|
||||
.join("");
|
||||
return `<svg viewBox="0 0 ${W} ${H}" role="img">${rows}</svg>`;
|
||||
}
|
||||
|
||||
function svgDonut(chart: ReportChart): string {
|
||||
const items = chart.items.slice(0, 6);
|
||||
const total = items.reduce((s, i) => s + Math.max(0, i.value), 0) || 1;
|
||||
const R = 56;
|
||||
const C = 2 * Math.PI * R;
|
||||
let offset = 0;
|
||||
const segs = items
|
||||
.map((it, i) => {
|
||||
const frac = Math.max(0, it.value) / total;
|
||||
const seg = `<circle cx="80" cy="80" r="${R}" fill="none" stroke="${P.accents[i % P.accents.length]}" stroke-width="20" stroke-dasharray="${(frac * C).toFixed(2)} ${C.toFixed(2)}" stroke-dashoffset="${(-offset * C).toFixed(2)}" transform="rotate(-90 80 80)" opacity="0.9"/>`;
|
||||
offset += frac;
|
||||
return seg;
|
||||
})
|
||||
.join("");
|
||||
const legend = items
|
||||
.map(
|
||||
(it, i) =>
|
||||
`<div class="lg"><i style="background:${P.accents[i % P.accents.length]}"></i>${esc(it.label)} <b>${esc(String(it.value))}</b></div>`,
|
||||
)
|
||||
.join("");
|
||||
return `<div class="donut"><svg viewBox="0 0 160 160" role="img">${segs}</svg><div class="lgs">${legend}</div></div>`;
|
||||
}
|
||||
|
||||
function svgRadar(chart: ReportChart): string {
|
||||
const items = chart.items.slice(0, 6);
|
||||
const n = Math.max(items.length, 3);
|
||||
const cx = 110;
|
||||
const cy = 95;
|
||||
const R = 70;
|
||||
const max = Math.max(...items.map((i) => i.value), 1);
|
||||
const pt = (i: number, r: number) => {
|
||||
const a = (Math.PI * 2 * i) / n - Math.PI / 2;
|
||||
return `${(cx + r * Math.cos(a)).toFixed(1)},${(cy + r * Math.sin(a)).toFixed(1)}`;
|
||||
};
|
||||
const grid = [0.33, 0.66, 1]
|
||||
.map(
|
||||
(k) =>
|
||||
`<polygon points="${Array.from({ length: n }, (_, i) => pt(i, R * k)).join(" ")}" class="gr"/>`,
|
||||
)
|
||||
.join("");
|
||||
const axes = Array.from(
|
||||
{ length: n },
|
||||
(_, i) => `<line x1="${cx}" y1="${cy}" x2="${pt(i, R).replace(",", '" y2="')}" class="gr"/>`,
|
||||
).join("");
|
||||
const poly = `<polygon points="${items.map((it, i) => pt(i, (Math.max(0, it.value) / max) * R)).join(" ")}" fill="${P.primary}33" stroke="${P.primary}" stroke-width="2"/>`;
|
||||
const labels = items
|
||||
.map((it, i) => {
|
||||
const [x, y] = pt(i, R + 16).split(",");
|
||||
return `<text x="${x}" y="${y}" class="cl" text-anchor="middle">${esc(it.label)}</text>`;
|
||||
})
|
||||
.join("");
|
||||
return `<svg viewBox="0 0 220 200" role="img">${grid}${axes}${poly}${labels}</svg>`;
|
||||
}
|
||||
|
||||
function chartHtml(chart: ReportChart): string {
|
||||
const body =
|
||||
chart.type === "donut" ? svgDonut(chart) : chart.type === "radar" ? svgRadar(chart) : svgBar(chart);
|
||||
return `<div class="card chart"><h3>${esc(chart.title || "图表")}</h3>${body}</div>`;
|
||||
}
|
||||
|
||||
const RISK_LABEL = { high: "高", mid: "中", low: "低" } as const;
|
||||
|
||||
function riskChips(risks: ReportSeatRisk[]): string {
|
||||
if (risks.length === 0) return "";
|
||||
return `<div class="chips">${risks
|
||||
.map((r) => {
|
||||
const color = P.risk[r.level]; // 主题语义色:错误/警告/成功
|
||||
return `<span class="chip" style="border-color:${color};color:${color};background:${color}14">${RISK_LABEL[r.level]}风险 · ${esc(r.label)}</span>`;
|
||||
})
|
||||
.join("")}</div>`;
|
||||
}
|
||||
|
||||
function metricBars(metrics: ReportSeatMetric[]): string {
|
||||
if (metrics.length === 0) return "";
|
||||
return `<div class="metrics">${metrics
|
||||
.map(
|
||||
(m, i) =>
|
||||
`<div class="metric"><span>${esc(m.label)}</span><div class="track"><div class="fill" style="width:${m.value}%;background:${P.accents[i % P.accents.length]}"></div></div><b>${m.value}</b></div>`,
|
||||
)
|
||||
.join("")}</div>`;
|
||||
}
|
||||
|
||||
/** 依赖双向 chips:deps = 本席位依赖谁;supports = 谁依赖本席位(反向推导)。 */
|
||||
function depChips(seat: ReportSeat, all: ReportSeat[]): string {
|
||||
const byId = new Map(all.map((s) => [s.id, s]));
|
||||
const supports = all.filter((s) => s.dependsOn.includes(seat.id));
|
||||
const dep = seat.dependsOn
|
||||
.map((d) => byId.get(d))
|
||||
.filter((s): s is ReportSeat => !!s)
|
||||
.map((s) => `<a class="dep" href="#${esc(s.id)}">依赖 → ${esc(s.name)}</a>`)
|
||||
.join("");
|
||||
const sup = supports
|
||||
.map((s) => `<a class="dep sup" href="#${esc(s.id)}">${esc(s.name)} ← 承接本席位</a>`)
|
||||
.join("");
|
||||
if (!dep && !sup) return "";
|
||||
return `<div class="deps">${dep}${sup}</div>`;
|
||||
}
|
||||
|
||||
/** 渲染大屏多页 HTML(自包含 · 零 JS · :target 导航 · 跟随应用主题)。 */
|
||||
export function renderDashboardHtml(
|
||||
data: ReportData,
|
||||
opts?: { generatedAt?: string; theme?: DashboardTheme },
|
||||
): string {
|
||||
P = PALETTES[opts?.theme ?? "dark"];
|
||||
const seats = data.seats;
|
||||
const nav =
|
||||
`<a class="tab" href="#overview">总览</a>` +
|
||||
seats.map((s) => `<a class="tab" href="#${esc(s.id)}">${esc(s.name)}</a>`).join("");
|
||||
|
||||
const kpis = data.kpis
|
||||
.map(
|
||||
(k, i) =>
|
||||
`<div class="card kpi"><span class="klabel">${esc(k.label)}</span><div class="kval" style="color:${P.accents[i % P.accents.length]}">${esc(k.value)}<small>${esc(k.unit ?? "")}</small>${
|
||||
k.trend === "up" ? '<i class="tr up">▲</i>' : k.trend === "down" ? '<i class="tr dn">▼</i>' : ""
|
||||
}</div></div>`,
|
||||
)
|
||||
.join("");
|
||||
|
||||
const seatCards = seats
|
||||
.map((s, i) => {
|
||||
const color = P.accents[i % P.accents.length];
|
||||
return `<a class="card seat" href="#${esc(s.id)}" style="--ac:${color}">
|
||||
<div class="shead"><i></i><h3>${esc(s.name)}</h3><span class="go">进入席位页 →</span></div>
|
||||
<p>${esc(s.summary || "(无摘要)")}</p>
|
||||
${metricBars(s.metrics.slice(0, 2))}
|
||||
${riskChips(s.risks.slice(0, 2))}
|
||||
</a>`;
|
||||
})
|
||||
.join("");
|
||||
|
||||
const timeline = data.timeline.length
|
||||
? `<div class="card tl"><h3>执行路线</h3><ol>${data.timeline
|
||||
.map((t) => `<li><b>${esc(t.label)}</b><span>${esc(t.desc)}</span></li>`)
|
||||
.join("")}</ol></div>`
|
||||
: "";
|
||||
|
||||
const consensusPoints = data.consensus.points.map((p) => `<li>${esc(p)}</li>`).join("");
|
||||
|
||||
const overview = `<section class="page" id="overview">
|
||||
<div class="kpis">${kpis}</div>
|
||||
<div class="grid2">
|
||||
<div class="card consensus"><h3>总控最终共识</h3>
|
||||
<p class="headline">${esc(data.consensus.headline || "(未提供)")}</p>
|
||||
<ul>${consensusPoints}</ul>
|
||||
<a class="more" href="#consensus-modal">查看详情</a>
|
||||
</div>
|
||||
<div class="charts">${data.charts.map(chartHtml).join("")}</div>
|
||||
</div>
|
||||
<h2 class="sec">席位交付总览 <small>点击卡片进入席位专页</small></h2>
|
||||
<div class="seats">${seatCards}</div>
|
||||
${timeline}
|
||||
</section>`;
|
||||
|
||||
const seatPages = seats
|
||||
.map((s, i) => {
|
||||
const color = P.accents[i % P.accents.length];
|
||||
const prev = seats[(i - 1 + seats.length) % seats.length];
|
||||
const next = seats[(i + 1) % seats.length];
|
||||
const sections = s.sections
|
||||
.map(
|
||||
(sec) =>
|
||||
`<div class="card sect"><h3>${esc(sec.heading)}</h3><ul>${sec.bullets
|
||||
.map((b) => `<li>${esc(b)}</li>`)
|
||||
.join("")}</ul></div>`,
|
||||
)
|
||||
.join("");
|
||||
return `<section class="page" id="${esc(s.id)}" style="--ac:${color}">
|
||||
<div class="pbar">
|
||||
<a class="back" href="#overview">← 返回总览</a>
|
||||
<div class="pnav"><a href="#${esc(prev.id)}">‹ ${esc(prev.name)}</a><a href="#${esc(next.id)}">${esc(next.name)} ›</a></div>
|
||||
</div>
|
||||
<header class="phead"><i></i><div><h2>${esc(s.name)}</h2><p>${esc(s.summary)}</p></div></header>
|
||||
${depChips(s, seats)}
|
||||
<div class="psections">${sections || '<div class="card sect"><p class="empty">(该席位无结构化小节)</p></div>'}</div>
|
||||
<div class="grid2">
|
||||
${s.metrics.length ? `<div class="card"><h3>量化指标</h3>${metricBars(s.metrics)}</div>` : ""}
|
||||
${s.risks.length ? `<div class="card"><h3>风险提示</h3>${riskChips(s.risks)}</div>` : ""}
|
||||
</div>
|
||||
</section>`;
|
||||
})
|
||||
.join("");
|
||||
|
||||
const modal = `<div class="modal" id="consensus-modal"><div class="mbody card">
|
||||
<a class="mclose" href="#overview">×</a>
|
||||
<h3>总控最终共识 · 全部要点</h3>
|
||||
<p class="headline">${esc(data.consensus.headline)}</p>
|
||||
<ul>${consensusPoints}</ul>
|
||||
</div></div>`;
|
||||
|
||||
const generated = opts?.generatedAt ? `生成于 ${esc(opts.generatedAt)}` : "";
|
||||
|
||||
return `<!doctype html>${RT_DASHBOARD_MARKER}
|
||||
<html lang="zh-CN"><head><meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>${esc(data.title)}</title>
|
||||
<style>
|
||||
/* 主题色板(light=浅红色 UI 规范 / dark=深蓝色 UI 规范,渲染时注入) */
|
||||
:root{--line:${P.cardBorder};--txt:${P.text};--dim:${P.textSecondary};--strong:${P.textStrong};
|
||||
--primary:${P.primary};--link:${P.link};--heading:${P.heading};--track:${P.trackBg}}
|
||||
*{box-sizing:border-box;margin:0;padding:0}
|
||||
body{font-family:"Noto Sans S Chinese","Microsoft YaHei",system-ui,sans-serif;color:var(--txt);min-height:100vh;
|
||||
background:${P.bgGradient};background-color:${P.bgPage};background-attachment:fixed}
|
||||
body::before{content:"";position:fixed;inset:0;pointer-events:none;opacity:.6;
|
||||
background:linear-gradient(${P.gridLine} 1px,transparent 1px),linear-gradient(90deg,${P.gridLine} 1px,transparent 1px);
|
||||
background-size:42px 42px}
|
||||
.top{position:sticky;top:0;z-index:5;display:flex;flex-wrap:wrap;align-items:center;gap:12px;
|
||||
padding:14px 26px;background:${P.navBg};backdrop-filter:blur(6px);border-bottom:1px solid var(--line)}
|
||||
.top h1{font-size:21px;letter-spacing:2px;background:${P.titleColor};
|
||||
-webkit-background-clip:text;background-clip:text;color:transparent;white-space:nowrap}
|
||||
.top .sub{font-size:12px;color:var(--dim)}
|
||||
.top .meta{margin-left:auto;font-size:11px;color:var(--dim)}
|
||||
nav{display:flex;flex-wrap:wrap;gap:8px;padding:10px 26px;border-bottom:1px solid var(--line)}
|
||||
.tab{font-size:12px;padding:5px 14px;border:1px solid var(--line);border-radius:2px;color:var(--dim);text-decoration:none;transition:.15s}
|
||||
.tab:hover{color:${P.primary};border-color:${P.primary};box-shadow:0 0 10px ${P.primary}40}
|
||||
main{padding:20px 26px 40px;max-width:1480px;margin:0 auto}
|
||||
.page{display:none;animation:fi .25s ease}
|
||||
#overview{display:block}
|
||||
.page:target{display:block}
|
||||
body:has(.page:target) #overview:not(:target){display:none}
|
||||
@keyframes fi{from{opacity:0;transform:translateY(6px)}to{opacity:1}}
|
||||
/* 卡片:规范圆角 4px;浅色实底白卡 + 轻阴影,深色深蓝渐变 + 内发光 */
|
||||
.card{position:relative;border:1px solid var(--line);border-radius:4px;padding:16px 18px;
|
||||
background:${P.card};box-shadow:${P.cardGlow}}
|
||||
.card::before,.card::after{content:"";position:absolute;width:14px;height:14px;border-color:${P.bracket};border-style:solid;opacity:.55}
|
||||
.card::before{top:-1px;left:-1px;border-width:2px 0 0 2px;border-radius:4px 0 0 0}
|
||||
.card::after{bottom:-1px;right:-1px;border-width:0 2px 2px 0;border-radius:0 0 4px 0}
|
||||
.card h3{font-size:13px;letter-spacing:1.5px;color:var(--heading);margin-bottom:10px}
|
||||
.kpis{display:grid;grid-template-columns:repeat(auto-fit,minmax(170px,1fr));gap:14px;margin-bottom:18px}
|
||||
.kpi .klabel{font-size:11px;color:var(--dim);letter-spacing:1px}
|
||||
.kpi .kval{font-size:30px;font-weight:800;margin-top:4px;font-family:"D-DIN",Consolas,monospace}
|
||||
.kpi small{font-size:12px;margin-left:4px;color:var(--dim)}
|
||||
.kpi .tr{font-style:normal;font-size:12px;margin-left:6px}.tr.up{color:${P.risk.low}}.tr.dn{color:${P.risk.high}}
|
||||
.grid2{display:grid;grid-template-columns:1fr 1fr;gap:14px;margin-bottom:18px}
|
||||
@media(max-width:980px){.grid2{grid-template-columns:1fr}}
|
||||
.consensus .headline{font-size:15px;font-weight:700;color:var(--strong);margin-bottom:8px}
|
||||
.consensus ul{padding-left:18px;display:grid;gap:5px;font-size:12.5px;color:var(--txt)}
|
||||
.consensus .more{display:inline-block;margin-top:10px;font-size:11px;color:${P.link};text-decoration:none;border-bottom:1px dashed ${P.link}}
|
||||
.charts{display:grid;gap:14px}
|
||||
.chart svg{width:100%;height:auto}
|
||||
.cl{fill:var(--dim);font-size:11px}.cv{fill:var(--txt);font-size:11px;font-weight:700}
|
||||
.ct{fill:var(--track)}.gr{fill:none;stroke:${P.primary}2e;stroke-width:1}
|
||||
.donut{display:flex;align-items:center;gap:14px}.donut svg{width:130px;flex:none}
|
||||
.lgs{display:grid;gap:5px}.lg{font-size:11.5px;color:var(--dim)}.lg b{color:var(--txt);margin-left:4px}
|
||||
.lg i{display:inline-block;width:9px;height:9px;border-radius:2px;margin-right:6px}
|
||||
.sec{font-size:14px;letter-spacing:2px;color:var(--heading);margin:6px 0 12px}
|
||||
.sec small{font-size:11px;color:var(--dim);font-weight:400;margin-left:8px}
|
||||
.seats{display:grid;grid-template-columns:repeat(auto-fill,minmax(280px,1fr));gap:14px;margin-bottom:18px}
|
||||
.seat{display:block;text-decoration:none;color:inherit;transition:.15s}
|
||||
.seat:hover{border-color:var(--ac);box-shadow:0 0 16px ${P.primary}30;transform:translateY(-2px)}
|
||||
.shead{display:flex;align-items:center;gap:8px;margin-bottom:8px}
|
||||
.shead i{width:8px;height:8px;border-radius:50%;background:var(--ac);box-shadow:0 0 8px var(--ac)}
|
||||
.shead h3{margin:0;flex:1}
|
||||
.go{font-size:10.5px;color:var(--dim)}
|
||||
.seat:hover .go{color:var(--ac)}
|
||||
.seat p{font-size:12px;color:var(--dim);line-height:1.6;margin-bottom:8px}
|
||||
.metrics{display:grid;gap:7px}
|
||||
.metric{display:flex;align-items:center;gap:8px;font-size:11px;color:var(--dim)}
|
||||
.metric span{width:72px;flex:none}.metric b{width:26px;text-align:right;color:var(--txt)}
|
||||
.track{flex:1;height:7px;border-radius:4px;background:var(--track);overflow:hidden}
|
||||
.fill{height:100%;border-radius:4px}
|
||||
.chips{display:flex;flex-wrap:wrap;gap:6px;margin-top:8px}
|
||||
.chip{font-size:10.5px;padding:2px 9px;border:1px solid;border-radius:2px}
|
||||
.tl ol{list-style:none;display:grid;grid-template-columns:repeat(auto-fit,minmax(180px,1fr));gap:10px;counter-reset:tl}
|
||||
.tl li{position:relative;padding:10px 12px 10px 14px;border-left:2px solid ${P.primary};background:${P.primary}10;border-radius:0 4px 4px 0}
|
||||
.tl b{display:block;font-size:12.5px;color:var(--heading);margin-bottom:3px}
|
||||
.tl span{font-size:11px;color:var(--dim);line-height:1.5}
|
||||
.pbar{display:flex;justify-content:space-between;align-items:center;margin-bottom:14px;font-size:12px}
|
||||
.pbar a{color:${P.link};text-decoration:none}.pnav{display:flex;gap:14px}.pnav a{color:var(--dim)}.pnav a:hover{color:${P.link}}
|
||||
.phead{display:flex;align-items:center;gap:12px;margin-bottom:12px}
|
||||
.phead i{width:10px;height:34px;border-radius:3px;background:var(--ac);box-shadow:0 0 10px var(--ac)}
|
||||
.phead h2{font-size:19px;letter-spacing:2px;color:var(--strong)}
|
||||
.phead p{font-size:12px;color:var(--dim);margin-top:3px}
|
||||
.deps{display:flex;flex-wrap:wrap;gap:8px;margin-bottom:14px}
|
||||
.dep{font-size:11px;padding:3px 11px;border:1px dashed ${P.link};border-radius:2px;color:${P.link};text-decoration:none}
|
||||
.dep.sup{border-color:${P.risk.low};color:${P.risk.low}}
|
||||
.dep:hover{background:${P.link}1a}
|
||||
.psections{display:grid;grid-template-columns:repeat(auto-fit,minmax(300px,1fr));gap:14px;margin-bottom:14px}
|
||||
.sect ul{padding-left:16px;display:grid;gap:6px;font-size:12.5px;line-height:1.6}
|
||||
.sect .empty{font-size:12px;color:var(--dim)}
|
||||
.modal{display:none;position:fixed;inset:0;z-index:20;background:${P.modalMask};padding:6vh 16px}
|
||||
.modal:target{display:flex;justify-content:center;align-items:flex-start}
|
||||
.mbody{max-width:680px;width:100%;max-height:84vh;overflow:auto}
|
||||
.mbody ul{padding-left:18px;display:grid;gap:6px;font-size:13px}
|
||||
.mclose{position:absolute;top:8px;right:14px;font-size:20px;color:var(--dim);text-decoration:none}
|
||||
.mclose:hover{color:${P.risk.high}}
|
||||
</style></head>
|
||||
<body>
|
||||
<header class="top"><h1>${esc(data.title)}</h1><span class="sub">${esc(data.subtitle)}</span><span class="meta">${generated}</span></header>
|
||||
<nav>${nav}</nav>
|
||||
<main>
|
||||
${overview}
|
||||
${seatPages}
|
||||
</main>
|
||||
${modal}
|
||||
</body></html>`;
|
||||
}
|
||||
Reference in new issue
Block a user