圆桌第三步与业务链条增强:主题跟随/插话暂停/提示词优化/结构化流程图
- 结果绘制跟随日/夜间主题(深色按深蓝 UI 规范令牌绘制),提示词注入真实生成时间 - 绘制支持暂停与随时插话(线程存活时免带原料续线程省 token)、失败自动重试一次、草稿主题不匹配提示条 - 总结报告优先执行用户最终总结要求(结构化输出/重点席位可整体替换默认章节) - 业务链条总控提示词与各阶段目标加「AI 优化」按钮(新接口 POST /api/roundtable-chains/optimize-prompt) - 总结报告 flow-json 结构化流程图:流式增量绘制、最新连线蚂蚁线动画、拖拽/缩放/复位/全屏、节点详情弹窗、沙箱切换按钮/无沙箱自动打开 - roundtable-report / roundtable-summary 两个内置智能体 SOUL 更新(双主题、多轮修改允许读底稿、KPI 估算标注、流程数据契约) Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
1 parent
a4a9a4d26e
commit
df8bf895ef
13 files changed
+1600
-83
No files matched your search
@@ -0,0 +1,122 @@
|
||||
/**
|
||||
* flow-graph.ts 纯函数单测。
|
||||
* 运行方式(项目无 vitest,对齐 dag-types.test.ts):
|
||||
* npx esbuild src/roundtable-planning/lib/flow-graph.test.ts --bundle --format=esm \
|
||||
* --platform=node --outfile=.tmp-tests/flow-graph.test.mjs
|
||||
* node --test .tmp-tests/flow-graph.test.mjs
|
||||
*/
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
|
||||
import {
|
||||
extractFlowGraph,
|
||||
layoutFlowGraph,
|
||||
stripFlowFence,
|
||||
} from "./flow-graph";
|
||||
|
||||
const FULL = [
|
||||
"报告正文……",
|
||||
"```flow-json",
|
||||
'{"title":"方案执行流程","nodes":[',
|
||||
'{"id":"n1","label":"环境评估","type":"stage","detail":"评估现场环境"},',
|
||||
'{"id":"n2","label":"编制方案","type":"task","from":["n1"]},',
|
||||
'{"id":"n3","label":"是否可行","type":"decision","from":[{"id":"n2","label":"评审"}]}',
|
||||
"]}",
|
||||
"```",
|
||||
].join("\n");
|
||||
|
||||
test("extractFlowGraph:完整块解析出节点/边/标题", () => {
|
||||
const g = extractFlowGraph(FULL);
|
||||
assert.ok(g);
|
||||
assert.equal(g.title, "方案执行流程");
|
||||
assert.equal(g.nodes.length, 3);
|
||||
assert.equal(g.nodes[0].type, "stage");
|
||||
assert.deepEqual(g.edges, [
|
||||
{ from: "n1", to: "n2" },
|
||||
{ from: "n2", to: "n3", label: "评审" },
|
||||
]);
|
||||
});
|
||||
|
||||
test("extractFlowGraph:流式半截(fence 未闭合 + 尾对象截断)只取完整节点", () => {
|
||||
const partial = [
|
||||
"正文",
|
||||
"```flow-json",
|
||||
'{"title":"T","nodes":[',
|
||||
'{"id":"a","label":"A","type":"start"},',
|
||||
'{"id":"b","label":"B","type":"task","from":["a"]},',
|
||||
'{"id":"c","label":"C","ty', // 截断
|
||||
].join("\n");
|
||||
const g = extractFlowGraph(partial);
|
||||
assert.ok(g);
|
||||
assert.equal(g.nodes.length, 2);
|
||||
assert.deepEqual(g.edges, [{ from: "a", to: "b" }]);
|
||||
});
|
||||
|
||||
test("extractFlowGraph:未知 type 落 task、重复 id 去重、悬空边丢弃", () => {
|
||||
const text = [
|
||||
"```flow-json",
|
||||
'{"nodes":[',
|
||||
'{"id":"x","label":"X","type":"banana"},',
|
||||
'{"id":"x","label":"X-dup","type":"task"},',
|
||||
'{"id":"y","label":"Y","type":"risk","from":["x","ghost"]}',
|
||||
"]}",
|
||||
"```",
|
||||
].join("\n");
|
||||
const g = extractFlowGraph(text);
|
||||
assert.ok(g);
|
||||
assert.equal(g.nodes.length, 2);
|
||||
assert.equal(g.nodes[0].type, "task");
|
||||
assert.equal(g.nodes[0].label, "X");
|
||||
assert.deepEqual(g.edges, [{ from: "x", to: "y" }]);
|
||||
});
|
||||
|
||||
test("extractFlowGraph:无 fence / 无完整节点返回 null", () => {
|
||||
assert.equal(extractFlowGraph("普通回复,没有结构化数据"), null);
|
||||
assert.equal(extractFlowGraph('```flow-json\n{"nodes":[{"id":"a"'), null);
|
||||
});
|
||||
|
||||
test("extractFlowGraph:兼容独立 edges 数组(source/target 别名)", () => {
|
||||
const text = [
|
||||
"```flow-json",
|
||||
'{"nodes":[{"id":"a","label":"A"},{"id":"b","label":"B"}],',
|
||||
'"edges":[{"source":"a","target":"b","label":"走"}]}',
|
||||
"```",
|
||||
].join("\n");
|
||||
const g = extractFlowGraph(text);
|
||||
assert.ok(g);
|
||||
assert.deepEqual(g.edges, [{ from: "a", to: "b", label: "走" }]);
|
||||
});
|
||||
|
||||
test("stripFlowFence:闭合块替换为引导语并保留前后文", () => {
|
||||
const out = stripFlowFence(FULL, false);
|
||||
assert.ok(out.includes("报告正文"));
|
||||
assert.ok(!out.includes("```flow-json"));
|
||||
assert.ok(out.includes("已生成结构化流程数据"));
|
||||
});
|
||||
|
||||
test("stripFlowFence:未闭合(流式中)用「正在输出」措辞", () => {
|
||||
const out = stripFlowFence('正文\n```flow-json\n{"nodes":[', true);
|
||||
assert.ok(out.includes("正在输出结构化流程数据"));
|
||||
assert.ok(!out.includes("```flow-json"));
|
||||
});
|
||||
|
||||
test("layoutFlowGraph:按前驱分层(根 0 层,子层递增),保持原始顺序", () => {
|
||||
const g = extractFlowGraph(FULL)!;
|
||||
const positioned = layoutFlowGraph(g);
|
||||
assert.equal(positioned[0].y, 0);
|
||||
assert.ok(positioned[1].y > positioned[0].y);
|
||||
assert.ok(positioned[2].y > positioned[1].y);
|
||||
assert.deepEqual(positioned.map((n) => n.id), ["n1", "n2", "n3"]);
|
||||
});
|
||||
|
||||
test("layoutFlowGraph:环不死循环", () => {
|
||||
const text = [
|
||||
"```flow-json",
|
||||
'{"nodes":[{"id":"a","label":"A","from":["b"]},{"id":"b","label":"B","from":["a"]}]}',
|
||||
"```",
|
||||
].join("\n");
|
||||
const g = extractFlowGraph(text)!;
|
||||
const positioned = layoutFlowGraph(g);
|
||||
assert.equal(positioned.length, 2);
|
||||
positioned.forEach((n) => assert.ok(Number.isFinite(n.x) && Number.isFinite(n.y)));
|
||||
});
|
||||
@@ -0,0 +1,282 @@
|
||||
/**
|
||||
* Step 3「总结报告」结构化流程图 —— flow-json 契约的纯函数层。
|
||||
*
|
||||
* 契约(与 roundtable-summary SOUL 对齐):用户要求结构化输出/流程图时,总结智能体
|
||||
* 在对话回复末尾追加一个 ```flow-json 代码块:
|
||||
*
|
||||
* ```flow-json
|
||||
* {"title":"…","nodes":[
|
||||
* {"id":"n1","label":"…","type":"stage","detail":"…"},
|
||||
* {"id":"n2","label":"…","type":"task","detail":"…","from":["n1"]},
|
||||
* {"id":"n3","label":"…","type":"decision","detail":"…","from":[{"id":"n2","label":"是"}]}
|
||||
* ]}
|
||||
* ```
|
||||
*
|
||||
* 关键设计:**边长在节点身上**(`from` = 前驱列表)——流式输出时每解析出一个完整
|
||||
* 节点,它的连线随之出现,前端给「最新节点的连线」挂蚂蚁线动画即可实现「画到哪、
|
||||
* 哪条线在爬」。解析必须**容错半截 JSON**(流式中代码块尚未闭合):用平衡括号扫描
|
||||
* 把 nodes 数组里**已完整**的对象逐个 JSON.parse,截断的尾对象直接忽略。
|
||||
*/
|
||||
|
||||
export type FlowNodeType =
|
||||
| "start"
|
||||
| "end"
|
||||
| "stage"
|
||||
| "task"
|
||||
| "decision"
|
||||
| "risk"
|
||||
| "deliverable"
|
||||
| "role";
|
||||
|
||||
export interface FlowGraphNode {
|
||||
id: string;
|
||||
label: string;
|
||||
type: FlowNodeType;
|
||||
detail?: string;
|
||||
}
|
||||
|
||||
export interface FlowGraphEdge {
|
||||
from: string;
|
||||
to: string;
|
||||
label?: string;
|
||||
}
|
||||
|
||||
export interface FlowGraphData {
|
||||
title: string;
|
||||
nodes: FlowGraphNode[];
|
||||
edges: FlowGraphEdge[];
|
||||
}
|
||||
|
||||
/** 各类型节点的配色(浅底 + 深字 + 强调点),前端按 type 区分颜色。 */
|
||||
export const FLOW_NODE_TYPE_META: Record<
|
||||
FlowNodeType,
|
||||
{ label: string; bg: string; border: string; text: string; dot: string }
|
||||
> = {
|
||||
start: { label: "开始", bg: "#f1f5f9", border: "#94a3b8", text: "#334155", dot: "#64748b" },
|
||||
end: { label: "结束", bg: "#f1f5f9", border: "#94a3b8", text: "#334155", dot: "#64748b" },
|
||||
stage: { label: "阶段", bg: "#eff6ff", border: "#60a5fa", text: "#1d4ed8", dot: "#3b82f6" },
|
||||
task: { label: "任务", bg: "#ecfeff", border: "#22d3ee", text: "#0e7490", dot: "#06b6d4" },
|
||||
decision: { label: "判断", bg: "#fffbeb", border: "#fbbf24", text: "#b45309", dot: "#f59e0b" },
|
||||
risk: { label: "风险", bg: "#fef2f2", border: "#f87171", text: "#b91c1c", dot: "#ef4444" },
|
||||
deliverable: { label: "交付物", bg: "#f0fdf4", border: "#4ade80", text: "#15803d", dot: "#22c55e" },
|
||||
role: { label: "角色", bg: "#faf5ff", border: "#c084fc", text: "#7e22ce", dot: "#a855f7" },
|
||||
};
|
||||
|
||||
const VALID_TYPES = new Set<string>(Object.keys(FLOW_NODE_TYPE_META));
|
||||
|
||||
export const FLOW_FENCE_OPEN = "```flow-json";
|
||||
|
||||
/**
|
||||
* 平衡括号扫描:从 `key`(如 `"nodes"`)后面的 `[` 开始,把数组里**已完整闭合**的
|
||||
* 顶层 `{…}` 逐个 JSON.parse 收集;跳过字符串内的括号与转义;数组未闭合(流式半截)
|
||||
* 时收集到哪算哪,截断的尾对象忽略。
|
||||
*/
|
||||
function collectObjects(text: string, key: string): Record<string, unknown>[] {
|
||||
const keyIdx = text.indexOf(key);
|
||||
if (keyIdx < 0) return [];
|
||||
const arrStart = text.indexOf("[", keyIdx);
|
||||
if (arrStart < 0) return [];
|
||||
const out: Record<string, unknown>[] = [];
|
||||
let depth = 0;
|
||||
let objStart = -1;
|
||||
let inStr = false;
|
||||
let esc = false;
|
||||
for (let i = arrStart + 1; i < text.length; i++) {
|
||||
const ch = text[i];
|
||||
if (inStr) {
|
||||
if (esc) esc = false;
|
||||
else if (ch === "\\") esc = true;
|
||||
else if (ch === '"') inStr = false;
|
||||
continue;
|
||||
}
|
||||
if (ch === '"') {
|
||||
inStr = true;
|
||||
continue;
|
||||
}
|
||||
if (ch === "{") {
|
||||
if (depth === 0) objStart = i;
|
||||
depth++;
|
||||
continue;
|
||||
}
|
||||
if (ch === "}") {
|
||||
depth--;
|
||||
if (depth === 0 && objStart >= 0) {
|
||||
try {
|
||||
const parsed = JSON.parse(text.slice(objStart, i + 1)) as unknown;
|
||||
if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
|
||||
out.push(parsed as Record<string, unknown>);
|
||||
}
|
||||
} catch {
|
||||
/* 截断/非法对象:跳过 */
|
||||
}
|
||||
objStart = -1;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (ch === "]" && depth === 0) break; // 数组正常闭合
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function asString(v: unknown): string {
|
||||
return typeof v === "string" ? v.trim() : "";
|
||||
}
|
||||
|
||||
/** 把 raw 节点对象规范化;id/label 缺失返回 null。未知 type 落到 task。 */
|
||||
function toNode(raw: Record<string, unknown>): FlowGraphNode | null {
|
||||
const id = asString(raw.id);
|
||||
const label = asString(raw.label) || asString(raw.name);
|
||||
if (!id || !label) return null;
|
||||
const rawType = asString(raw.type).toLowerCase();
|
||||
const type = (VALID_TYPES.has(rawType) ? rawType : "task") as FlowNodeType;
|
||||
const detail = asString(raw.detail) || asString(raw.description) || undefined;
|
||||
return { id, label, type, detail };
|
||||
}
|
||||
|
||||
/** 节点 `from` 字段(前驱列表,元素是 "n1" 或 {id:"n1",label:"是"})→ 入边列表。 */
|
||||
function edgesFromNode(raw: Record<string, unknown>, nodeId: string): FlowGraphEdge[] {
|
||||
const from = raw.from ?? raw.prev;
|
||||
if (!Array.isArray(from)) return [];
|
||||
const out: FlowGraphEdge[] = [];
|
||||
for (const entry of from) {
|
||||
if (typeof entry === "string" && entry.trim()) {
|
||||
out.push({ from: entry.trim(), to: nodeId });
|
||||
} else if (entry && typeof entry === "object") {
|
||||
const o = entry as Record<string, unknown>;
|
||||
const fromId = asString(o.id) || asString(o.from);
|
||||
if (!fromId) continue;
|
||||
const label = asString(o.label) || undefined;
|
||||
out.push({ from: fromId, to: nodeId, label });
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** 独立 `edges` 数组(兼容形态:{from,to,label} / {source,target})→ 边。 */
|
||||
function toEdge(raw: Record<string, unknown>): FlowGraphEdge | null {
|
||||
const from = asString(raw.from) || asString(raw.source);
|
||||
const to = asString(raw.to) || asString(raw.target);
|
||||
if (!from || !to) return null;
|
||||
const label = asString(raw.label) || undefined;
|
||||
return { from, to, label };
|
||||
}
|
||||
|
||||
/**
|
||||
* 从(可能流式半截的)回复文本里提取最后一个 ```flow-json 块并解析。
|
||||
* 没有 fence 或一个完整节点都没有 → null。
|
||||
*/
|
||||
export function extractFlowGraph(text: string): FlowGraphData | null {
|
||||
const start = text.lastIndexOf(FLOW_FENCE_OPEN);
|
||||
if (start < 0) return null;
|
||||
let body = text.slice(start + FLOW_FENCE_OPEN.length);
|
||||
const close = body.indexOf("```");
|
||||
if (close >= 0) body = body.slice(0, close);
|
||||
|
||||
const titleMatch = /"title"\s*:\s*"((?:[^"\\]|\\.)*)"/.exec(body);
|
||||
let title = "";
|
||||
if (titleMatch) {
|
||||
try {
|
||||
title = JSON.parse(`"${titleMatch[1]}"`) as string;
|
||||
} catch {
|
||||
title = titleMatch[1];
|
||||
}
|
||||
}
|
||||
|
||||
const rawNodes = collectObjects(body, '"nodes"');
|
||||
const nodes: FlowGraphNode[] = [];
|
||||
const seen = new Set<string>();
|
||||
const edges: FlowGraphEdge[] = [];
|
||||
for (const raw of rawNodes) {
|
||||
const node = toNode(raw);
|
||||
if (!node || seen.has(node.id)) continue;
|
||||
seen.add(node.id);
|
||||
nodes.push(node);
|
||||
edges.push(...edgesFromNode(raw, node.id));
|
||||
}
|
||||
// 兼容独立 edges 数组(contract 主推 from-on-node,但模型可能两种都写)。
|
||||
for (const raw of collectObjects(body, '"edges"')) {
|
||||
const edge = toEdge(raw);
|
||||
if (edge) edges.push(edge);
|
||||
}
|
||||
if (nodes.length === 0) return null;
|
||||
|
||||
// 只保留两端节点都已出现的边 + 去重(流式中前驱未出现的边等下一轮解析再进来)。
|
||||
const edgeKeys = new Set<string>();
|
||||
const validEdges = edges.filter((e) => {
|
||||
if (!seen.has(e.from) || !seen.has(e.to) || e.from === e.to) return false;
|
||||
const key = `${e.from}->${e.to}`;
|
||||
if (edgeKeys.has(key)) return false;
|
||||
edgeKeys.add(key);
|
||||
return true;
|
||||
});
|
||||
return { title, nodes, edges: validEdges };
|
||||
}
|
||||
|
||||
/**
|
||||
* 把回复里的 flow-json 块替换成一句人话(气泡里不展示生 JSON)。
|
||||
* 块未闭合(流式中)→「正在输出」措辞;已闭合 → 引导去看流程图画布。
|
||||
*/
|
||||
export function stripFlowFence(text: string, streaming: boolean): string {
|
||||
const start = text.lastIndexOf(FLOW_FENCE_OPEN);
|
||||
if (start < 0) return text;
|
||||
const after = text.slice(start + FLOW_FENCE_OPEN.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}`;
|
||||
}
|
||||
|
||||
// ── 分层布局(自上而下:前驱层 +1,同层横向铺开)────────────────────────────
|
||||
|
||||
export interface PositionedFlowNode extends FlowGraphNode {
|
||||
x: number;
|
||||
y: number;
|
||||
}
|
||||
|
||||
export const FLOW_NODE_W = 176;
|
||||
const X_GAP = 224;
|
||||
const Y_GAP = 132;
|
||||
|
||||
/** 最长路径分层(环保护:访问中的节点按 0 层处理,保证终止)。 */
|
||||
export function layoutFlowGraph(data: FlowGraphData): PositionedFlowNode[] {
|
||||
const preds = new Map<string, string[]>();
|
||||
for (const e of data.edges) {
|
||||
const list = preds.get(e.to);
|
||||
if (list) list.push(e.from);
|
||||
else preds.set(e.to, [e.from]);
|
||||
}
|
||||
const memo = new Map<string, number>();
|
||||
const visiting = new Set<string>();
|
||||
const layerOf = (id: string): number => {
|
||||
const cached = memo.get(id);
|
||||
if (cached !== undefined) return cached;
|
||||
if (visiting.has(id)) return 0; // 环:斩断,按根层处理
|
||||
visiting.add(id);
|
||||
const ps = preds.get(id) ?? [];
|
||||
const layer = ps.length === 0 ? 0 : Math.max(...ps.map(layerOf)) + 1;
|
||||
visiting.delete(id);
|
||||
memo.set(id, layer);
|
||||
return layer;
|
||||
};
|
||||
|
||||
const byLayer = new Map<number, FlowGraphNode[]>();
|
||||
for (const n of data.nodes) {
|
||||
const layer = layerOf(n.id);
|
||||
const list = byLayer.get(layer);
|
||||
if (list) list.push(n);
|
||||
else byLayer.set(layer, [n]);
|
||||
}
|
||||
|
||||
const pos = new Map<string, { x: number; y: number }>();
|
||||
for (const [layer, nodes] of byLayer) {
|
||||
const rowWidth = (nodes.length - 1) * X_GAP;
|
||||
nodes.forEach((n, i) => {
|
||||
pos.set(n.id, { x: i * X_GAP - rowWidth / 2, y: layer * Y_GAP });
|
||||
});
|
||||
}
|
||||
// 保持原始(流式)顺序输出,方便调用方做「最新节点」判断。
|
||||
return data.nodes.map((n) => ({ ...n, ...pos.get(n.id)! }));
|
||||
}
|
||||
Reference in new issue
Block a user