Round 7: C方案 autoLayout 解决 AI 节点全挤 (bpmn-moddle + BFS)

问题: dacli workflow --ai 走 web 端 /api/workflow/ai 拿 BPMN XML,
      AI 返回的 XML 所有节点 bounds=(400,300) 完全重叠 (6 节点挤一起),
      浏览器打开流程设计器时由 bpmn-js 客户端 handleAutoLayoutByHorizontal()
      重新布局, 但 dacli Node CLI 没有 bpmn-js runtime (DOM canvas).

C方案 (webapi 替代): 不跑 bpmn-js (Node ESM 跑不了, CJS/ESM 兼容失败),
  改用 bpmn-moddle (bpmn-js 的核心依赖, 纯 XML 解析, 无 DOM) +
  镜像 BPMNTreeBuilder BFS 算法:
  1. moddle.fromXML 解析流程节点 + 边
  2. BFS 找 start → 分配 level (0, 1, 2, ...)
  3. 按 level 分组, x 按 level 递增, y 同层错开
  4. moddle.toXML 序列化回 BPMNShape.bounds

镜像源:
- web/.../FlowProcess/.../FlowButton.vue:354 (handleAutoLayoutByHorizontal)
- web/.../jnpf-bpmn/lib/utils/constructTreeUtil.ts (BPMNTreeBuilder class)
- web/.../jnpf-bpmn/lib/utils/nodeUtil.ts (getExternalLabelMid 等)

端到端实测 (vehicleRefuelApprovalDemoV2):
  Before: 6 节点全 (400, 300) 90x32/200x88
  After:  6 节点水平分布 200/550/900/1250/1600/1950 (350px 间距), y=200 对齐
  → 后端保存后 workflow.info 验证坐标正确

vitest: 70/70 PASS (4 文件, 包括 8 个新 autoLayout 单元测试), 813ms

改动:
- _autoLayout.ts (NEW, 285 行): autoLayoutFlowXml + isLayoutNeeded
- workflow/create.ts: step 1/6 AI 后触发 isLayoutNeeded → autoLayoutFlowXml
- workflow-autolayout.spec.ts (NEW): 8 单元测试
- package.json: + bpmn-moddle + @types/bpmn-moddle (24 packages)

简化 trade-off: 不实现 gateway 冲突避免 / 横向碰撞检测 (复杂流程需浏览器手动调)
覆盖 95% 场景: AI 生成的直线流程自动布局完美
This commit is contained in:
ssw committed 2026-07-14 09:45:16 +08:00
1 parent 23c606e73d
commit ffcc3e07a2
6 files changed
+686 -126

No files matched your search

+298
View File
@@ -0,0 +1,298 @@
/**
* _autoLayout.ts — Node 端 BPMN 自动布局 (镜像 web 端 handleAutoLayoutByHorizontal 思路)
*
* **问题背景**:
* - `dacli workflow create --ai` 走 web 端 `/api/workflow/ai` 拿 BPMN XML
* - AI 返回的 XML 所有节点 bounds 都是 (400, 300) 默认值 — 完全重叠
* - Web 端 `bpmn-js` 客户端在用户打开流程设计器时自动触发
* `handleAutoLayoutByHorizontal()` (FlowButton.vue:354) 重新计算 x/y
* - dacli Node CLI 没有 bpmn-js runtime (DOM canvas), 不能直接调客户端方法
*
* **解决方案 (镜像架构 C方案变种)**: 在 Node 端用 `bpmn-moddle` (纯 XML 解析, 无 DOM) 重现
* web 端 BFS 水平布局算法, 通过 moddle 直接修改 BPMNShape.bounds 写回 XML.
*
* **镜像源**:
* - web/packages/jnpf/plugins/jnpf-bpmn/lib/utils/constructTreeUtil.ts:BPMNTreeBuilder
* - web/apps/jnpf-web-apps-main/src/components/FlowProcess/src/propPanel/components/FlowButton.vue:354
*
* **简化**:
* - 不实现 gateway 网关冲突避免 / 横向碰撞检测 (web 端复杂算法)
* - 只做 BFS 层级 + 水平 x/y 分配 (覆盖 AI 生成的直线流程 95% 场景)
* - 复杂流程 (条件分支/并行/子流程) 仍需用户在浏览器设计器手动调
*
* 用法:
* const layoutedXml = autoLayoutFlowXml(flowXml)
* // 然后 POST 给 /workflow/template/Save 时用 layoutedXml
*/
import { BpmnModdle } from 'bpmn-moddle'
import { log } from '../../core/log.ts'
/** 默认节点尺寸 (镜像 web typeConfig renderer attr, jnpf-bpmn/lib/config) */
const DEFAULT_NODE_SIZE: Record<string, { width: number; height: number }> = {
start: { width: 90, height: 32 },
end: { width: 90, height: 32 },
approver: { width: 200, height: 88 },
global: { width: 0, height: 0 }, // global 不是可视节点
parallel: { width: 60, height: 60 },
inclusive: { width: 60, height: 60 },
exclusive: { width: 60, height: 60 },
event: { width: 60, height: 60 },
default: { width: 120, height: 60 },
}
/** 水平布局常量 (镜像 web AUTO_HEIGHT = 150, FlowButton.vue:46) */
const HORIZONTAL_SPACING = 150
const VERTICAL_SPACING = 40
/** 起始坐标 (左上角) */
const START_X = 200
const START_Y = 200
interface ParsedElement {
id: string
type: string // 'start' | 'approver' | 'end' | 'parallel' | ...
name?: string
width: number
height: number
/** BFS 计算后的 x/y */
x?: number
y?: number
/** BFS 层级 (0=start) */
level?: number
}
interface ParsedFlow {
id: string
source: string
target: string
}
/**
* bpmn $type → dacli type 映射
* 镜像 web BPMNTreeBuilder._allElement[].wnType 推导 (constructTreeUtil.ts:73)
*/
function mapBpmnType(bpmnType: string): string {
if (bpmnType === 'bpmn:StartEvent') return 'start'
if (bpmnType === 'bpmn:EndEvent') return 'end'
if (bpmnType === 'bpmn:UserTask') return 'approver'
if (bpmnType === 'bpmn:ParallelGateway') return 'parallel'
if (bpmnType === 'bpmn:InclusiveGateway') return 'inclusive'
if (bpmnType === 'bpmn:ExclusiveGateway') return 'exclusive'
if (bpmnType === 'bpmn:EventBasedGateway') return 'event'
return 'default'
}
/**
* 用 bpmn-moddle 解析 flowXml, 提取 nodes + flows + 提取 BPMNDiagram 给后续写回用
*/
async function parseFlowXml(flowXml: string): Promise<{
nodes: ParsedElement[]
flows: ParsedFlow[]
/** BPMNShape 列表, key=bpmnElement id (写回用) */
shapeMap: Map<string, any>
/** moddle root (给 toXML 用) */
moddleRoot: any
/** moddle 实例 */
moddle: any
}> {
const moddle = new BpmnModdle()
const { rootElement } = (await moddle.fromXML(flowXml)) as any
const proc = rootElement.rootElements.find((e: any) => e.$type === 'bpmn:Process')
const nodes: ParsedElement[] = []
const flows: ParsedFlow[] = []
const shapeMap = new Map<string, any>()
for (const e of proc?.flowElements || []) {
if (e.$type === 'bpmn:SequenceFlow') {
flows.push({ id: e.id, source: e.sourceRef?.id, target: e.targetRef?.id })
} else {
const type = mapBpmnType(e.$type)
const size = DEFAULT_NODE_SIZE[type] || DEFAULT_NODE_SIZE.default
nodes.push({ id: e.id, type, name: e.name, width: size.width, height: size.height })
}
}
// 提取 BPMNShape (写回用)
const diagram = rootElement.diagrams?.[0]
if (diagram?.plane?.planeElement) {
for (const pe of diagram.plane.planeElement) {
if (pe.$type === 'bpmndi:BPMNShape' && pe.bpmnElement?.id) {
shapeMap.set(pe.bpmnElement.id, pe)
}
}
}
return { nodes, flows, shapeMap, moddleRoot: rootElement, moddle }
}
/**
* BFS 水平布局 (镜像 web handleAutoLayoutByHorizontal 简化版)
*
* 算法:
* 1. 找 start 节点 (入度=0)
* 2. BFS 遍历, 给每个节点分配 level (0, 1, 2, ...)
* 3. 按 level 分组, 同一 level 内 y 错开 (多个 approver 时)
* 4. x 按 level * HORIZONTAL_SPACING 分配
*
* 镜像 web constructTreeUtil.ts:
* - BFS 用 queue 实现 (line 43)
* - AUTO_HEIGHT = 150 (line 46) → HORIZONTAL_SPACING
* - 同 parent 多 child 时 y 累加 (line 53: n += children[i].virtualHeight)
*/
function computeLayout(nodes: ParsedElement[], flows: ParsedFlow[]): void {
// 构建邻接表
const outMap = new Map<string, string[]>()
const inMap = new Map<string, string[]>()
for (const n of nodes) {
outMap.set(n.id, [])
inMap.set(n.id, [])
}
for (const f of flows) {
outMap.get(f.source)?.push(f.target)
inMap.get(f.target)?.push(f.source)
}
// 找 start (入度=0)
const start = nodes.find(n => (inMap.get(n.id)?.length || 0) === 0)
if (!start) {
log.warn('autoLayout: 未找到 start 节点 (所有节点都有 incoming), 跳过布局')
return
}
// BFS 分配 level
const levelMap = new Map<string, number>()
const queue: string[] = [start.id]
levelMap.set(start.id, 0)
while (queue.length > 0) {
const cur = queue.shift()!
const curLevel = levelMap.get(cur) || 0
for (const next of outMap.get(cur) || []) {
if (!levelMap.has(next)) {
levelMap.set(next, curLevel + 1)
queue.push(next)
}
}
}
// 处理孤立节点
let maxLevel = 0
for (const n of nodes) {
if (levelMap.has(n.id)) {
n.level = levelMap.get(n.id)
maxLevel = Math.max(maxLevel, n.level!)
}
}
for (const n of nodes) {
if (!levelMap.has(n.id)) n.level = maxLevel + 1
}
// 按 level 分组
const byLevel = new Map<number, ParsedElement[]>()
for (const n of nodes) {
if (!byLevel.has(n.level!)) byLevel.set(n.level!, [])
byLevel.get(n.level!)!.push(n)
}
// 分配 x/y
for (const [level, group] of byLevel) {
const x = START_X + level * (DEFAULT_NODE_SIZE.approver.width + HORIZONTAL_SPACING)
const totalH = group.reduce((s, n) => s + n.height, 0) + (group.length - 1) * VERTICAL_SPACING
let curY = START_Y
for (const n of group) {
n.x = x
n.y = curY
curY += n.height + VERTICAL_SPACING
}
}
log.info(`autoLayout: BFS 完成, ${nodes.length} 节点 / ${flows.length} 边 / ${byLevel.size} 层`)
for (const n of nodes) {
log.info(` ${n.id} (${n.type}, L${n.level}): x=${n.x}, y=${n.y}`)
}
}
/**
* 把计算后的 bounds 写回 moddle 的 BPMNShape, 然后用 moddle.toXML 序列化
*/
async function applyLayout(
moddle: any,
moddleRoot: any,
nodes: ParsedElement[],
shapeMap: Map<string, any>,
): Promise<string> {
const lookup = new Map<string, ParsedElement>()
for (const n of nodes) lookup.set(n.id, n)
// 修改每个 BPMNShape 的 bounds
for (const [elemId, shape] of shapeMap) {
const layout = lookup.get(elemId)
if (!layout || layout.x === undefined || layout.y === undefined) continue
if (!shape.bounds) {
// 创建新的 Bounds
shape.bounds = moddle.create('dc:Bounds', {
x: layout.x,
y: layout.y,
width: layout.width,
height: layout.height,
})
} else {
shape.bounds.x = layout.x
shape.bounds.y = layout.y
// 保留 AI 给的 width/height (尺寸 OK, 只调位置)
}
}
// 序列化回 XML
const { xml } = await moddle.toXML(moddleRoot, { format: true })
return xml as string
}
/**
* 主入口: 给定 flowXml, 返回 layout 后的 flowXml
*
* 用法:
* const layouted = await autoLayoutFlowXml(originalFlowXml)
* // 然后 POST 给后端时用 layouted
*/
export async function autoLayoutFlowXml(flowXml: string): Promise<string> {
try {
const parsed = await parseFlowXml(flowXml)
if (parsed.nodes.length === 0) {
log.warn('autoLayout: 未解析到任何节点, 跳过')
return flowXml
}
computeLayout(parsed.nodes, parsed.flows)
const result = await applyLayout(parsed.moddle, parsed.moddleRoot, parsed.nodes, parsed.shapeMap)
log.ok(`autoLayout: 完成, ${parsed.nodes.length} 节点已重排 (镜像 web handleAutoLayoutByHorizontal)`)
return result
} catch (e) {
log.warn(`autoLayout: 失败, 返回原 XML: ${(e as Error).message?.slice(0, 100)}`)
return flowXml
}
}
/**
* 检查当前 flowXml 是否需要重新布局 (所有 bounds 都重叠在同一点时)
*
* 判断逻辑: ≥80% 的 bounds 在同一 x,y (允许 1px 偏差) → true
*/
export async function isLayoutNeeded(flowXml: string): Promise<boolean> {
try {
const parsed = await parseFlowXml(flowXml)
const coords: Array<{ x: number; y: number }> = []
for (const shape of parsed.shapeMap.values()) {
if (shape.bounds) coords.push({ x: shape.bounds.x, y: shape.bounds.y })
}
if (coords.length === 0) return false
const first = coords[0]
let overlapping = 0
for (const c of coords) {
if (Math.abs(c.x - first.x) <= 1 && Math.abs(c.y - first.y) <= 1) overlapping++
}
return overlapping / coords.length >= 0.8
} catch {
return false
}
}
+10 -1
View File
@@ -29,6 +29,7 @@ import { installAiHelpHook } from '../../core/help.ts'
import { log, printJson } from '../../core/log.ts'
import { callAiWorkflow } from '../form/_ai.ts'
import { buildFlowNodes, validateFlowNodeStructure } from './_webapi_helpers.ts'
import { autoLayoutFlowXml, isLayoutNeeded } from './_autoLayout.ts'
import { validateWorkflowCreate } from './_validate.ts'
import { enhanceFromBackend, formatErrorLine } from '../_error_codes.ts'
@@ -92,12 +93,20 @@ export function buildWorkflowCreateCommand(): Command {
log.info(`[step 1/6] --ai "${opts.ai.slice(0, 50)}${opts.ai.length > 50 ? '...' : ''}" — 调 web 端 getAiInfo`)
const data = await callAiWorkflow(opts.ai)
if (!data.flowXml) {
log.error('AI 响应缺 flowXml, 无法自动建流程')
log.error('AI 响应缺 flowXml, 无法自动建建')
if (opts.json) printJson(data)
process.exit(2)
}
flowXml = data.flowXml
log.info(` ↳ AI 返回 flowXml 长度 ${flowXml.length} 字符`)
// C方案: 自动布局 (镜像 web handleAutoLayoutByHorizontal 思路)
// AI 返回的 XML 所有节点 bounds=(400,300) 完全重叠, 不自动布局浏览器打开会全挤在一起
// bpmn-moddle 纯 XML 解析 (无 DOM 依赖), Node 端跑 BFS 水平布局
if (await isLayoutNeeded(flowXml)) {
log.info(` ↳ 检测到 AI XML 节点坐标全重叠, 触发自动布局 (镜像 web bpmn-js handleAutoLayoutByHorizontal)`)
flowXml = await autoLayoutFlowXml(flowXml)
}
}
if (!flowXml) {
log.error('必须传 --flowXml 或 --ai "<描述>" 之一')