From 75be5f485e5b90b6d42284d953104c4c5601d971 Mon Sep 17 00:00:00 2001 From: ThearchyHelios Date: Thu, 24 Sep 2026 22:58:54 +0800 Subject: [PATCH] =?UTF-8?q?=E7=94=BB=E5=B8=83=E4=B8=8A=E7=9A=84=E7=BA=BF?= =?UTF-8?q?=E4=B8=8D=E5=86=8D=E5=8F=A0=E5=9C=A8=E4=B8=80=E8=B5=B7=EF=BC=9A?= =?UTF-8?q?=E6=8E=92=E7=89=88=E6=8C=89=E8=BD=A6=E9=81=93=E7=95=99=E8=B5=B0?= =?UTF-8?q?=E5=BB=8A=EF=BC=8C=E8=B5=B0=E7=BA=BF=E4=B8=8D=E5=86=8D=E4=BA=A4?= =?UTF-8?q?=E7=BB=99=20smoothstep?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 原来所有边都交给 React Flow 的 smoothstep,它的竖直段一律落在源和目标的 正中间。同一列的边于是全挤在同一个 x 上:一张"入口扇出三路 → 归并 → 分支 → 出具/驳回"的图上,跨层的 a3→join 和 m2→join 的横段**完全压在同一条线 上**,长边还直接从"归并B"卡片中间穿过去。排版那边同样糙:同层按 id 字典序 竖排,所以 out_no 排在 out_yes 上面("n" < "y"),分支的 yes/no 是反的; 层内没有任何减少交叉的排序;层间距写死 300。 后端 app/engine/layout.py 重写成分层布局:先剔回边再按最长路径分层(loop 的回边不参与分层,否则循环体会被压到循环节点左边);层内中位数启发式上下扫 六轮取交叉最少的一版,分支/循环的出口再按声明顺序占位重排;y 先均匀堆叠再按 邻居重心迭代松弛,同列节点因此和上下游对齐,长边也走得直;最后按"穿过这条 走廊的连线在竖直方向最多重叠几条"给走廊留宽——区间图上的贪心染色,和前端 用的是同一套,走廊留窄了前端再聪明也只能把线叠起来。 前端 canvas/routing.ts 自己算走线:出边沿右边缘错开、入边沿左边缘错开(入边 按上游纵向位置排序),竖直段按区间染色分配车道——真叠在一起的才各占一条, 首尾相接的(同一个扇出点)共用一条,看起来就是一条总线;跨层的长边和循环的 回边在中间各列的纵向占用里找空档绕过去,不再压过卡片。边换成自定义组件后 React Flow 不再自动加动画类,实测确认 .edge-active 仍然生效。 顺带修掉"排完版看不见图":整张图换过坐标后(自动排版 / Copilot 生成完 / 切图)自动重新取景。坐标变了视角没变,人盯着的是一片空白。 新增 scripts/check-canvas-layout.mjs:把夹具图交给真后端 /api/copilot/layout 排版,再直接 import('/src/canvas/routing.ts') 用页面上跑的那份代码算路径, 按几何断言没有两条线压在同一段上、没有线穿过别人的卡片、两端都接在节点边缘, 另有 1325 条随机坐标的 fuzz 防手拖之后算出 NaN 路径(NaN 的 path 什么都不 画,界面上就是"线没了",一声不吭)。这条检查做过变异验证——把 laneX 改成 永远返回走廊中点,它立刻报 a3→join × m2→join,正是原图上那处重叠。 285 passed(新增 12 条排版不变量)。check-ui 69 项通过,唯一失败项"本地哈希 要标出没有语义能力"已 git stash 到基线复现,与本次无关。 --- README.md | 27 +- backend/app/api/copilot.py | 39 +-- backend/app/engine/layout.py | 414 ++++++++++++++++++++++++ backend/app/seed.py | 2 +- backend/tests/test_layout.py | 180 +++++++++++ frontend/src/canvas/FlowCanvas.tsx | 94 +++--- frontend/src/canvas/FlowEdge.tsx | 54 ++++ frontend/src/canvas/NodeCard.tsx | 3 +- frontend/src/canvas/routing.ts | 502 +++++++++++++++++++++++++++++ frontend/src/store/studio.ts | 15 +- scripts/check-canvas-layout.mjs | 328 +++++++++++++++++++ 11 files changed, 1573 insertions(+), 85 deletions(-) create mode 100644 backend/app/engine/layout.py create mode 100644 backend/tests/test_layout.py create mode 100644 frontend/src/canvas/FlowEdge.tsx create mode 100644 frontend/src/canvas/routing.ts create mode 100644 scripts/check-canvas-layout.mjs diff --git a/README.md b/README.md index dc5ba946..d2189434 100644 --- a/README.md +++ b/README.md @@ -152,6 +152,12 @@ flowchart LR 连线即并行:单个节点连出多条边构成 fan-out,多条边汇入同一节点时自动等待汇聚。 +自动排版按拓扑分层:并行的支路落在同一列,层内按中位数启发式排序以减少交叉, +分支节点的出口按 yes/no 的声明顺序自上而下,循环的回边不参与分层(否则循环体会 +被压到循环节点左边)。层与层之间按"穿过这条走廊的连线在竖直方向最多重叠几条" +预留走廊宽度,前端 `canvas/routing.ts` 据此给每条线分配独立的竖直车道——扇出、 +汇聚的线因此不会叠在同一段上,跨层的长边则从没有节点的空档绕过去。 + --- ## 节点类型 @@ -211,11 +217,12 @@ backend/ FastAPI + LangGraph app/api/ REST + WebSocket frontend/ React 19 + React Flow + Zustand src/canvas/nodeDefs.ts 节点元数据——属性面板、节点库、连接桩均由其驱动 + src/canvas/routing.ts 连线走线:端口错开、走廊车道、长边绕行 src/run/decode.ts 事件流 → 人类可读步骤的唯一翻译层 src/store/studio.ts 画布状态 + 事件流到高亮的映射 environment.yml conda 环境定义 scripts/dev.sh 一键启动 -scripts/check-*.mjs 三层前端验证脚本 +scripts/check-*.mjs 前端验证脚本 ``` --- @@ -384,23 +391,29 @@ agent 侧同样会收到实情,并被告知可直接查询 `information_schema ## 开发与验证 ```bash -# 后端:271 个测试 +# 后端:285 个测试 cd backend && pytest tests # 前端类型检查 cd frontend && npx tsc -b -# 三层前端验证(需先启动 ./scripts/dev.sh) -node scripts/check-decode.mjs # 事件 → 步骤的翻译是否正确 -node scripts/check-stream.mjs # 助手流组件渲染是否正确 -node scripts/check-ui.mjs # 真浏览器端到端:URL 寻址、会话、运行详情 -node scripts/e2e-check.mjs # 冒烟:打开画布 → 选模板 → 运行 → 观察高亮 +# 前端验证(需先启动 ./scripts/dev.sh) +node scripts/check-decode.mjs # 事件 → 步骤的翻译是否正确 +node scripts/check-stream.mjs # 助手流组件渲染是否正确 +node scripts/check-ui.mjs # 真浏览器端到端:URL 寻址、会话、运行详情 +node scripts/check-canvas-layout.mjs # 排版与连线几何:线有没有叠、有没有穿过卡片 +node scripts/e2e-check.mjs # 冒烟:打开画布 → 选模板 → 运行 → 观察高亮 ``` 三层前端验证的分工:`check-decode` 守「翻译对不对」,`check-stream` 守「画出来对不对」, `check-ui` 守「整条路走得通不通」。三者可各自通过而合起来是坏的——例如 Step 字段全部正确, 组件却将其渲染为一屏转义 JSON。 +`check-canvas-layout` 单独守「图好不好看」里唯一能算的那部分:它把夹具图交给后端 +`/api/copilot/layout` 排版,再直接 `import('/src/canvas/routing.ts')` 用页面上正在跑的那份 +走线代码算路径,然后按几何断言——没有两条线压在同一段上、没有线从别人的卡片中间穿过去、 +每条线的两端都接在节点边缘。连线叠成一团时 `check-ui` 和 `e2e-check` 一个字都不会说。 + ## License This project is **source-available** and is licensed under the [PolyForm Noncommercial License 1.0.0](https://polyformproject.org/licenses/noncommercial/1.0.0). diff --git a/backend/app/api/copilot.py b/backend/app/api/copilot.py index 92262407..836746f2 100644 --- a/backend/app/api/copilot.py +++ b/backend/app/api/copilot.py @@ -12,6 +12,7 @@ from sqlalchemy.ext.asyncio import AsyncSession from app.db.base import get_session from app.db.models import Workflow +from app.engine.layout import auto_layout from app.engine.schema import GraphSpec, NodeType, validate_graph from app.engine.state import message_text from app.providers.factory import ModelSpec, ProviderNotConfigured, get_chat_model @@ -161,43 +162,6 @@ NODE_REFERENCE = """\ """ -def auto_layout(spec: GraphSpec, *, x_gap: int = 300, y_gap: int = 150) -> GraphSpec: - """按拓扑层级排版。 - - 模型生成的图只有结构没有坐标,全堆在原点就没法看了。 - 这里按最长路径分层:同层的节点竖排,层与层横向铺开。 - """ - nodes = spec.node_map() - depth: dict[str, int] = {} - - def compute(node_id: str, seen: frozenset[str]) -> int: - if node_id in depth: - return depth[node_id] - if node_id in seen: # 环:就地截断,避免递归爆栈 - return 0 - incoming = [e.source for e in spec.incoming(node_id) if e.source in nodes] - value = 0 if not incoming else 1 + max( - compute(src, seen | {node_id}) for src in incoming - ) - depth[node_id] = value - return value - - for node in spec.nodes: - compute(node.id, frozenset()) - - by_level: dict[int, list[str]] = {} - for node_id, level in depth.items(): - by_level.setdefault(level, []).append(node_id) - - for level, ids in sorted(by_level.items()): - offset = -(len(ids) - 1) * y_gap / 2 - for i, node_id in enumerate(sorted(ids)): - node = nodes[node_id] - node.position.x = 80 + level * x_gap - node.position.y = 300 + offset + i * y_gap - return spec - - class GenerateIn(BaseModel): instruction: str = Field(min_length=1, description="用自然语言描述想要的工作流") base_graph: dict[str, Any] | None = Field(default=None, description="在现有图上修改时传入") @@ -849,7 +813,6 @@ async def extract_template( """ from sqlalchemy import select as _sel - from app.api.copilot import auto_layout # 自引用仅为显式 from app.db.models import Run, RunEvent, Workflow, WorkflowVersion from app.core.artifact_store import graph_hash diff --git a/backend/app/engine/layout.py b/backend/app/engine/layout.py new file mode 100644 index 00000000..b34841bf --- /dev/null +++ b/backend/app/engine/layout.py @@ -0,0 +1,414 @@ +"""画布自动排版。 + +模型生成的图只有拓扑、没有坐标,全堆在原点就没法看;用户手拖过之后点 +「自动排版」也得重新摆一遍。这里做的是分层布局(Sugiyama 那条路)的简化版, +四步: + +1. **分层**:按最长路径定层。环上的回边先剔掉——不剔的话 loop 节点的回边 + 会把整张图压成一层,循环体跑到循环节点左边去。 +2. **层内排序**:中位数启发式上下扫,取交叉最少的那一版。并行分支因此会按 + 上游的相对位置排好,而不是按 id 字典序乱排(以前 `out_no` 排在 `out_yes` + 上面,因为 "n" < "y"——分支的 yes/no 就反着画)。 +3. **定 y**:先均匀堆叠,再按邻居重心迭代松弛。这一步是"同一列的节点和上下游 + 对齐"的关键,也是长边能走直、少拐弯的前提。 +4. **定 x**:层与层之间留一条走廊,走廊宽度按穿过它的连线在竖直方向的最大 + 重叠数算。前端拿这个宽度给每条线分配独立的竖直车道,线才不会叠在一起。 + ——走廊留窄了,前端再聪明也只能把线叠起来。 + +坐标的约定和前端 `canvas/routing.ts` 是一份契约,改这里要同步改那边: +节点宽 238(NodeCard 写死的),同列节点最小间距 ≥ MIN_ROW_GAP,走廊里 +竖直车道间距 LANE。 +""" + +from __future__ import annotations + +from collections import defaultdict, deque +from statistics import median + +from app.engine.schema import GraphNode, GraphSpec, NodeType + +#: 画布节点的宽度。前端 NodeCard 的 `width: 238` 是写死的,这里必须跟着它—— +#: 排版算出来的走廊是给连线用的,宽度估错了走廊就白留。 +NODE_W = 238 +#: 节点高度估算:标题栏 + 两行摘要。真实高度由前端量,这里只要不低估到让 +#: 同列节点撞上就行(前端按实测高度铺端口,能自己吸收这点误差)。 +NODE_H = 76 +#: 同列相邻节点的最小空隙。除了不撞,还要给横向走线留出能穿过去的空档。 +MIN_ROW_GAP = 56 +#: 连线离开节点后的第一段水平长度。 +STUB = 14 +#: 同一条走廊里相邻竖直车道的间距。 +LANE = 18 +#: 竖直区间重叠多少以内算"同一条道"。共用扇出点的两条线首尾相接,不该各占一条。 +LANE_OVERLAP_TOLERANCE = 6.0 +#: 走廊宽度下限/上限。上限是防止一个 20 路扇出的节点把整张图撑到屏幕外; +#: 顶到上限时前端会按可用宽度压缩车道间距。 +CORRIDOR_MIN = 96 +CORRIDOR_MAX = 420 +X_ORIGIN = 80 + +#: 分支节点的兜底出口,和前端 `sourceHandles()` 里的写法一致 +BRANCH_FALLBACK = "default" + + +def _height(node: GraphNode) -> float: + return NODE_H + + +def _dedupe_edges(spec: GraphSpec, nodes: dict[str, GraphNode]) -> list: + """丢掉悬空边和重复边,顺便给每条边定一个稳定的身份。 + + 自环(source == target)留到最后单独处理,它不参与分层。 + """ + seen: set[tuple[str, str, str]] = set() + out = [] + for e in spec.edges: + if e.source not in nodes or e.target not in nodes: + continue + key = (e.source, e.target, e.sourceHandle or "") + if key in seen: + continue + seen.add(key) + out.append(e) + return out + + +def _back_edges(nodes: dict[str, GraphNode], edges: list) -> set[tuple[str, str, str]]: + """DFS 森林里的回边。剔掉它们,剩下的必然是无环的。 + + 迭代式而不是递归:一张几百个节点的图不该因为递归深度挂掉。 + """ + adj: dict[str, list] = defaultdict(list) + for e in edges: + adj[e.source].append(e) + + WHITE, GREY, BLACK = 0, 1, 2 + state = dict.fromkeys(nodes, WHITE) + back: set[tuple[str, str, str]] = set() + + for root in nodes: + if state[root] != WHITE: + continue + stack: list[tuple[str, int]] = [(root, 0)] + state[root] = GREY + while stack: + node_id, i = stack[-1] + out = adj[node_id] + if i >= len(out): + state[node_id] = BLACK + stack.pop() + continue + stack[-1] = (node_id, i + 1) + edge = out[i] + target = edge.target + if state[target] == GREY: + back.add((edge.source, edge.target, edge.sourceHandle or "")) + elif state[target] == WHITE: + state[target] = GREY + stack.append((target, 0)) + return back + + +def _ranks( + nodes: dict[str, GraphNode], edges: list, back: set[tuple[str, str, str]], +) -> dict[str, int]: + """最长路径分层。并行分支会落在同一层,串行的才会被推开。""" + forward = [e for e in edges if (e.source, e.target, e.sourceHandle or "") not in back] + succ: dict[str, list[str]] = defaultdict(list) + indeg: dict[str, int] = dict.fromkeys(nodes, 0) + for e in forward: + succ[e.source].append(e.target) + indeg[e.target] += 1 + + rank = dict.fromkeys(nodes, 0) + queue = deque(sorted(n for n in nodes if indeg[n] == 0)) + while queue: + node_id = queue.popleft() + for target in succ[node_id]: + rank[target] = max(rank[target], rank[node_id] + 1) + indeg[target] -= 1 + if indeg[target] == 0: + queue.append(target) + return rank + + +def _handle_order(node: GraphNode) -> list[str]: + """节点出口在画布上从上到下的顺序。分支的 yes/no 就该是这个顺序。 + + 前端 `sourceHandles()` 决定出口怎么画,这里决定它们怎么排。两份必须一致, + 否则分支标签的上下关系会和连线对不上。 + """ + cfg = node.config + if node.type == NodeType.BRANCH: + keys = [ + str(c.get("key")) + for c in (cfg.get("cases") or []) + if isinstance(c, dict) and c.get("key") + ] + return keys + [BRANCH_FALLBACK] + if node.type == NodeType.LOOP: + return ["body", "done"] + if node.type == NodeType.HUMAN and cfg.get("mode", "approve") == "approve": + return ["approved", "rejected"] + return ["out"] + + +def _initial_orders( + spec: GraphSpec, nodes: dict[str, GraphNode], rank: dict[str, int], edges: list, +) -> list[list[str]]: + """第 0 层先按声明顺序(入口排前面),后面的层按上游位置摆一遍。""" + max_rank = max(rank.values(), default=0) + orders: list[list[str]] = [[] for _ in range(max_rank + 1)] + for node in spec.nodes: + if node.id in rank: + orders[rank[node.id]].append(node.id) + + preds: dict[str, list[str]] = defaultdict(list) + for e in edges: + preds[e.target].append(e.source) + + for r in range(1, max_rank + 1): + pos = {nid: i for i, nid in enumerate(orders[r - 1])} + here = {nid: i for i, nid in enumerate(orders[r])} + def key(nid: str) -> tuple[float, int]: + ps = [pos[p] for p in preds[nid] if p in pos] + return (median(ps) if ps else here[nid], here[nid]) + orders[r].sort(key=key) + return orders + + +def _crossings(orders: list[list[str]], rank: dict[str, int], edges: list) -> int: + """相邻两层之间的连线交叉数。只数跨一层的边——跨多层的长边没有虚拟节点, + 数不准,不如不数,免得把排序带偏。""" + total = 0 + by_rank: dict[int, list] = defaultdict(list) + for e in edges: + rs, rt = rank[e.source], rank[e.target] + if rt == rs + 1: + by_rank[rs].append(e) + for r, es in by_rank.items(): + if r + 1 >= len(orders): + continue + pos_s = {nid: i for i, nid in enumerate(orders[r])} + pos_t = {nid: i for i, nid in enumerate(orders[r + 1])} + pairs = [(pos_s[e.source], pos_t[e.target]) for e in es] + for i in range(len(pairs)): + for j in range(i + 1, len(pairs)): + a, b = pairs[i], pairs[j] + if (a[0] - b[0]) * (a[1] - b[1]) < 0: + total += 1 + return total + + +def _sweep( + orders: list[list[str]], neigh: dict[str, list[str]], down: bool, +) -> list[list[str]]: + """一轮中位数扫描。没邻居的节点按当前位置排,不被扫到队尾去。""" + result = [list(ids) for ids in orders] + seq = range(1, len(result)) if down else range(len(result) - 2, -1, -1) + for r in seq: + ref_rank = r - 1 if down else r + 1 + pos = {nid: i for i, nid in enumerate(result[ref_rank])} + here = {nid: i for i, nid in enumerate(result[r])} + + def key(nid: str) -> tuple[float, int]: + ps = [pos[p] for p in neigh[nid] if p in pos] + return (median(ps) if ps else here[nid], here[nid]) + + result[r].sort(key=key) + return result + + +def _minimize_crossings( + orders: list[list[str]], rank: dict[str, int], edges: list, + preds: dict[str, list[str]], succs: dict[str, list[str]], +) -> list[list[str]]: + best = [list(ids) for ids in orders] + best_score = _crossings(best, rank, edges) + for iteration in range(6): + orders = _sweep(orders, preds if iteration % 2 == 0 else succs, iteration % 2 == 0) + score = _crossings(orders, rank, edges) + if score < best_score: + best, best_score = [list(ids) for ids in orders], score + if best_score == 0: + break + return best + + +def _apply_handle_order( + orders: list[list[str]], spec: GraphSpec, nodes: dict[str, GraphNode], + rank: dict[str, int], +) -> None: + """分支/循环的出口有语义顺序,交叉再少也得让 yes 排在 no 上面。 + + 做法是"占位重排":这些后继本来占着层里的哪几个格子,就把它们按出口顺序 + 填回那几个格子——层里其他节点的相对次序不受影响。 + """ + outgoing: dict[str, list] = defaultdict(list) + for e in spec.edges: + outgoing[e.source].append(e) + + for node in spec.nodes: + handles = _handle_order(node) + if len(handles) < 2 or node.id not in nodes: + continue + outs = outgoing.get(node.id, []) + if not outs: + continue + groups: list[str] = [] + for handle in handles: + for e in outs: + if e.target not in nodes or e.target == node.id: + continue + if (e.sourceHandle or handles[0]) == handle and e.target not in groups: + groups.append(e.target) + # 同一层里按出口顺序重排;跨层的没法重排,跳过 + by_rank: dict[int, list[str]] = defaultdict(list) + for target in groups: + by_rank[rank[target]].append(target) + for r, targets in by_rank.items(): + if len(targets) < 2 or r >= len(orders): + continue + slots = sorted(orders[r].index(t) for t in targets if t in orders[r]) + if len(slots) != len(targets): + continue + for slot, target in zip(slots, targets): + orders[r][slot] = target + + +def _stack(orders: list[list[str]], nodes: dict[str, GraphNode], row_gap: float) -> dict[str, float]: + """每层先均匀堆叠,整层以 y=0 为中心。""" + y: dict[str, float] = {} + for ids in orders: + heights = [_height(nodes[i]) for i in ids] + total = sum(heights) + row_gap * (len(ids) - 1) + cursor = -total / 2 + for node_id, h in zip(ids, heights): + y[node_id] = cursor + h / 2 + cursor += h + row_gap + return y + + +def _relax( + y: dict[str, float], orders: list[list[str]], nodes: dict[str, GraphNode], + preds: dict[str, list[str]], succs: dict[str, list[str]], row_gap: float, + rounds: int = 6, +) -> None: + """按邻居重心松弛,再把同层节点推开到互不重叠。 + + 推开的正向扫描会把整层往下带,所以每层收尾要整体平移回重心——平移不改变 + 层内间距,重叠约束依然成立。 + """ + for iteration in range(rounds): + down = iteration % 2 == 0 + neigh = preds if down else succs + seq = range(len(orders)) if down else range(len(orders) - 1, -1, -1) + for r in seq: + ids = orders[r] + if not ids: + continue + desired = [] + for node_id in ids: + ys = [y[p] for p in neigh[node_id] if p in y] + desired.append(sum(ys) / len(ys) if ys else y[node_id]) + cursor: float | None = None + for i, node_id in enumerate(ids): + if cursor is None: + cursor = desired[i] + else: + gap = _height(nodes[ids[i - 1]]) / 2 + row_gap + _height(nodes[node_id]) / 2 + cursor = max(desired[i], cursor + gap) + y[node_id] = cursor + shift = sum(desired) / len(desired) - sum(y[i] for i in ids) / len(ids) + for node_id in ids: + y[node_id] += shift + + +def _lane_count(intervals: list[tuple[float, float]]) -> int: + """竖直走线至少要几条车道。 + + 就是区间图上的首次适应染色,按起点排序即最优。前端 `routing.ts` 用的是 + 同一套贪心,所以两边算出来的车道数一致——否则走廊留窄了,线还是会叠。 + """ + lanes: list[float] = [] + for start, end in sorted((min(a, b), max(a, b)) for a, b in intervals): + for i, lane_end in enumerate(lanes): + # 首尾相接(共用扇出点)不算冲突:那正是一条总线的样子。 + # 真叠在一起(重叠超过 TOLERANCE)才换一条道。 + if start >= lane_end - LANE_OVERLAP_TOLERANCE: + lanes[i] = max(lane_end, end) + break + else: + lanes.append(end) + return len(lanes) + + +def _corridor_width( + boundary: int, rank: dict[str, int], edges: list, y: dict[str, float], +) -> float: + """第 boundary 层和第 boundary+1 层之间要留多宽。 + + 穿过这条走廊的边在竖直方向最多重叠几条,就至少要几条车道。 + """ + intervals = [ + (y[e.source], y[e.target]) + for e in edges + if rank[e.source] <= boundary < rank[e.target] + ] + lanes = _lane_count(intervals) + if lanes <= 1: + return CORRIDOR_MIN + width = STUB * 2 + LANE * (lanes - 1) + 28 + return float(min(CORRIDOR_MAX, max(CORRIDOR_MIN, width))) + + +def auto_layout( + spec: GraphSpec, *, x_gap: int | None = None, y_gap: int | None = None, +) -> GraphSpec: + """给整张图重新分配坐标,返回同一个 spec(原地改坐标)。 + + `x_gap` / `y_gap` 是旧接口留下的旋钮,现在只当"走廊最窄多少、同列最少隔 + 多少"用:实际间距由拓扑算出来的车道需求决定,不再是固定 300/150。 + """ + if not spec.nodes: + return spec + + nodes = spec.node_map() + edges = _dedupe_edges(spec, nodes) + # 自环不参与分层:它不跨层,留着只会让"自己的前驱是自己"这种噪音渗进排序 + edges = [e for e in edges if e.source != e.target] + + back = _back_edges(nodes, edges) + rank = _ranks(nodes, edges, back) + + preds: dict[str, list[str]] = defaultdict(list) + succs: dict[str, list[str]] = defaultdict(list) + for e in edges: + preds[e.target].append(e.source) + succs[e.source].append(e.target) + + orders = _initial_orders(spec, nodes, rank, edges) + orders = _minimize_crossings(orders, rank, edges, preds, succs) + _apply_handle_order(orders, spec, nodes, rank) + + row_gap = float(y_gap) if y_gap else MIN_ROW_GAP + corridor_min = max(CORRIDOR_MIN, float(x_gap) - NODE_W) if x_gap else CORRIDOR_MIN + + y = _stack(orders, nodes, row_gap) + _relax(y, orders, nodes, preds, succs, row_gap) + + # 每个节点都有层,也就都在这两个表里;.get 的兜底是防"层算漏了"这种 + # 不该发生的情况——真漏了也把节点摆在图末尾,而不是让它掉在原点压住别人 + x: dict[str, float] = {} + cursor = float(X_ORIGIN) + for r, ids in enumerate(orders): + for node_id in ids: + x[node_id] = cursor + if r < len(orders) - 1: + width = _corridor_width(r, rank, edges, y) + cursor += NODE_W + max(width, corridor_min) + + for node in spec.nodes: + node.position.x = round(x.get(node.id, cursor), 1) + node.position.y = round(y.get(node.id, 0.0), 1) + return spec diff --git a/backend/app/seed.py b/backend/app/seed.py index 6bf17ebe..d86a7bee 100644 --- a/backend/app/seed.py +++ b/backend/app/seed.py @@ -357,7 +357,7 @@ async def seed_defaults() -> None: await session.commit() # --- 模板工作流 --- - from app.api.copilot import auto_layout + from app.engine.layout import auto_layout existing = {n for (n,) in await session.execute(select(Workflow.name))} added = 0 diff --git a/backend/tests/test_layout.py b/backend/tests/test_layout.py new file mode 100644 index 00000000..357c7679 --- /dev/null +++ b/backend/tests/test_layout.py @@ -0,0 +1,180 @@ +"""自动排版。 + +以前只有"按最长路径分层、同层按 id 字典序竖排"两条规则:并行的分支谁上谁下 +是随机的(`out_no` 排在 `out_yes` 上面,因为 "n" < "y"),层间距写死 300, +两个节点扇出到同一个目标时连线还会叠在一起。这些测试守的是重写之后的四条 +不变量:并行同层、分支按语义顺序、同列不重叠、走廊按车道需求留宽。 +""" + +from __future__ import annotations + +from app.engine.layout import NODE_W, auto_layout +from app.engine.schema import GraphSpec + + +def _graph(nodes, edges=()): + return GraphSpec.model_validate({ + "nodes": [ + {"id": n["id"], "type": n["type"], "position": {"x": 0, "y": 0}, + "data": {"label": n.get("label", ""), "config": n.get("config", {})}} + for n in nodes + ], + "edges": [ + {"source": e[0], "target": e[1], **({"sourceHandle": e[2]} if len(e) > 2 else {})} + for e in edges + ], + }) + + +def _parallel_graph(): + """一个入口扇出三条并行的 agent,再汇进同一个节点。""" + return _graph( + [ + {"id": "in", "type": "input"}, + {"id": "a1", "type": "agent"}, + {"id": "a2", "type": "agent"}, + {"id": "a3", "type": "agent"}, + {"id": "join", "type": "llm"}, + ], + [("in", "a1"), ("in", "a2"), ("in", "a3"), ("a1", "join"), ("a2", "join"), ("a3", "join")], + ) + + +def test_parallel_branches_share_a_column() -> None: + """并行的三条支路必须落在同一列:它们之间没有依赖,谁也不该排到谁后面。""" + spec = auto_layout(_parallel_graph()) + xs = {n.id: n.position.x for n in spec.nodes} + assert xs["a1"] == xs["a2"] == xs["a3"] + assert xs["in"] < xs["a1"] < xs["join"] + + +def test_parallel_branches_are_stacked_without_overlap() -> None: + spec = auto_layout(_parallel_graph()) + ys = sorted(n.position.y for n in spec.nodes if n.id.startswith("a")) + assert len(set(ys)) == 3 + # 同列相邻节点的纵向间距要够一个节点高度,否则卡片会叠在一起 + assert ys[1] - ys[0] >= 60 + assert ys[2] - ys[1] >= 60 + + +def test_branch_cases_keep_their_declared_order() -> None: + """分支的 yes/no 是语义顺序,不能按 id 字典序排("no" < "yes" 会反过来)。""" + spec = _graph( + [ + {"id": "gate", "type": "branch", + "config": {"cases": [{"key": "yes"}, {"key": "no"}]}}, + {"id": "out_no", "type": "output"}, + {"id": "out_yes", "type": "output"}, + ], + [("gate", "out_yes", "yes"), ("gate", "out_no", "no")], + ) + laid = auto_layout(spec) + pos = {n.id: n.position for n in laid.nodes} + assert pos["out_yes"].y < pos["out_no"].y + assert pos["out_yes"].x == pos["out_no"].x + + +def test_loop_body_stays_right_of_the_loop_node() -> None: + """回边不能被当成普通边参与分层——那样循环体会跑到循环节点左边去。""" + spec = _graph( + [ + {"id": "start", "type": "input"}, + {"id": "each", "type": "loop"}, + {"id": "body", "type": "llm"}, + {"id": "collect", "type": "transform"}, + {"id": "done", "type": "output"}, + ], + [ + ("start", "each"), + ("each", "body", "body"), + ("body", "collect"), + ("collect", "each"), + ("each", "done", "done"), + ], + ) + laid = auto_layout(spec) + pos = {n.id: n.position for n in laid.nodes} + assert pos["start"].x < pos["each"].x < pos["body"].x < pos["collect"].x + # 循环体出口排在结束出口上面 + assert pos["body"].y < pos["done"].y + + +def test_corridor_grows_with_lane_demand() -> None: + """扇出的线越多,走廊越宽——宽度不够,前端的车道就铺不开,线会叠回去。""" + narrow = auto_layout(_parallel_graph()) + wide = auto_layout(_graph( + [{"id": "in", "type": "input"}, {"id": "join", "type": "llm"}] + + [{"id": f"m{i}", "type": "llm"} for i in range(8)], + [("in", f"m{i}") for i in range(8)] + [(f"m{i}", "join") for i in range(8)], + )) + + def corridor(spec) -> float: + xs = sorted({n.position.x for n in spec.nodes}) + return min(b - a for a, b in zip(xs, xs[1:])) - NODE_W + + assert corridor(wide) > corridor(narrow) + + +def test_long_edges_do_not_widen_a_single_corridor_forever() -> None: + """走廊有上限。20 路扇出也不该把图撑到屏幕外面去。""" + spec = auto_layout(_graph( + [{"id": "in", "type": "input"}] + + [{"id": f"m{i}", "type": "llm"} for i in range(20)], + [("in", f"m{i}") for i in range(20)], + )) + xs = sorted({n.position.x for n in spec.nodes}) + assert xs[1] - xs[0] <= NODE_W + 460 + + +def test_same_column_never_overlaps() -> None: + """一整列节点两两之间必须留出至少一个卡片的高度。""" + spec = auto_layout(_graph( + [{"id": "in", "type": "input"}] + [{"id": f"n{i}", "type": "llm"} for i in range(12)], + [("in", f"n{i}") for i in range(12)], + )) + ys = sorted(n.position.y for n in spec.nodes if n.id != "in") + gaps = [b - a for a, b in zip(ys, ys[1:])] + assert gaps and min(gaps) >= 60 + + +def test_layout_is_stable_and_idempotent() -> None: + """同一张图排两次必须得到同一份坐标,否则保存后一刷新就跳。""" + first = auto_layout(_parallel_graph()).model_dump(mode="json") + second = auto_layout(GraphSpec.model_validate(first)).model_dump(mode="json") + assert [(n["id"], n["position"]) for n in first["nodes"]] == \ + [(n["id"], n["position"]) for n in second["nodes"]] + + +def test_layout_does_not_touch_the_graph_itself() -> None: + """排版只改坐标:节点、边、配置一个都不能丢,也不能多出来。""" + before = _parallel_graph() + ids = [(n.id, str(n.type)) for n in before.nodes] + edges = [(e.source, e.target, e.sourceHandle or "") for e in before.edges] + after = auto_layout(before) + assert [(n.id, str(n.type)) for n in after.nodes] == ids + assert [(e.source, e.target, e.sourceHandle or "") for e in after.edges] == edges + + +def test_cycle_does_not_hang_or_collapse() -> None: + """没有任何入口的纯环图也得排完,不能死循环。""" + spec = _graph( + [{"id": "x", "type": "llm"}, {"id": "y", "type": "llm"}], + [("x", "y"), ("y", "x")], + ) + laid = auto_layout(spec) + assert {n.id for n in laid.nodes} == {"x", "y"} + + +def test_dangling_edges_and_empty_graph_are_survivable() -> None: + assert auto_layout(GraphSpec()).nodes == [] + spec = auto_layout(_graph( + [{"id": "a", "type": "llm"}], + [("a", "ghost"), ("ghost", "a")], + )) + assert spec.nodes[0].position.x >= 0 + + +def test_self_loop_is_kept() -> None: + spec = auto_layout(_graph([{"id": "a", "type": "llm"}], [("a", "a")])) + assert spec.nodes[0].position.x >= 0 + assert len(spec.edges) == 1 diff --git a/frontend/src/canvas/FlowCanvas.tsx b/frontend/src/canvas/FlowCanvas.tsx index 96519ec9..99e09e22 100644 --- a/frontend/src/canvas/FlowCanvas.tsx +++ b/frontend/src/canvas/FlowCanvas.tsx @@ -1,13 +1,16 @@ -import { useCallback, useMemo, useRef } from 'react' +import { useCallback, useEffect, useMemo, useRef } from 'react' import { Background, BackgroundVariant, Controls, MiniMap, ReactFlow, ReactFlowProvider, useReactFlow, type Edge, } from '@xyflow/react' +import { FlowEdge, RoutingContext } from './FlowEdge' import { NodeCard } from './NodeCard' +import { buildRoutes } from './routing' import { useStudio } from '../store/studio' import type { NodeType } from '../types' const nodeTypes = { card: NodeCard } +const edgeTypes = { flow: FlowEdge } const NODE_COLOR: Record = { input: '#3fb950', output: '#a371f7', llm: '#4f8cff', agent: '#6366f1', @@ -18,23 +21,39 @@ const NODE_COLOR: Record = { function CanvasInner() { const wrapper = useRef(null) - const { screenToFlowPosition } = useReactFlow() + const { screenToFlowPosition, fitView } = useReactFlow() const nodes = useStudio((s) => s.nodes) const edges = useStudio((s) => s.edges) const activeEdges = useStudio((s) => s.activeEdges) + const fitRequest = useStudio((s) => s.fitRequest) const { onNodesChange, onEdgesChange, onConnect, addNode, select } = useStudio() + // 走线方案整张图算一次。节点尺寸要等 React Flow 量完才有,量到之后 + // nodes 会变,这里跟着重算,端口和车道就落到实测尺寸上。 + const routes = useMemo(() => buildRoutes(nodes, edges), [nodes, edges]) + // 正在流动的边加动画,让"数据走到哪了"看得见 const decorated = useMemo( () => edges.map((e) => activeEdges.includes(e.id) - ? { ...e, className: 'edge-active', animated: true } - : { ...e, className: undefined, animated: false }, + ? { ...e, type: 'flow', className: 'edge-active', animated: true } + : { ...e, type: 'flow', className: undefined, animated: false }, ), [edges, activeEdges], ) + // 自动排版 / Copilot 生成完之后把视角拉回图上。位置全变了却不重新取景, + // 人会盯着一片空白以为图没了。 + const firstFit = useRef(true) + useEffect(() => { + if (firstFit.current) { + firstFit.current = false + return + } + void fitView({ padding: 0.14, maxZoom: 1.1, duration: 280 }) + }, [fitRequest, fitView]) + const onDrop = useCallback( (event: React.DragEvent) => { event.preventDefault() @@ -47,38 +66,41 @@ function CanvasInner() { return (
- select(node.id)} - onPaneClick={() => select(null)} - onDrop={onDrop} - onDragOver={(e) => { - e.preventDefault() - e.dataTransfer.dropEffect = 'move' - }} - fitView - fitViewOptions={{ padding: 0.12, maxZoom: 1.1, minZoom: 0.5 }} - minZoom={0.2} - maxZoom={2} - defaultEdgeOptions={{ type: 'smoothstep' }} - proOptions={{ hideAttribution: true }} - deleteKeyCode={['Backspace', 'Delete']} - > - - - NODE_COLOR[(n.data as any)?.nodeType as string] ?? '#666'} - style={{ width: 140, height: 96 }} - /> - + + select(node.id)} + onPaneClick={() => select(null)} + onDrop={onDrop} + onDragOver={(e) => { + e.preventDefault() + e.dataTransfer.dropEffect = 'move' + }} + fitView + fitViewOptions={{ padding: 0.12, maxZoom: 1.1, minZoom: 0.5 }} + minZoom={0.2} + maxZoom={2} + defaultEdgeOptions={{ type: 'flow' }} + proOptions={{ hideAttribution: true }} + deleteKeyCode={['Backspace', 'Delete']} + > + + + NODE_COLOR[(n.data as any)?.nodeType as string] ?? '#666'} + style={{ width: 140, height: 96 }} + /> + +
) } diff --git a/frontend/src/canvas/FlowEdge.tsx b/frontend/src/canvas/FlowEdge.tsx new file mode 100644 index 00000000..90716440 --- /dev/null +++ b/frontend/src/canvas/FlowEdge.tsx @@ -0,0 +1,54 @@ +import { createContext, useContext } from 'react' +import { BaseEdge, EdgeLabelRenderer, getSmoothStepPath, type EdgeProps } from '@xyflow/react' +import type { Route } from './routing' + +/** 全画布的走线方案,由 FlowCanvas 算一次、所有边共用。 */ +export const RoutingContext = createContext | null>(null) + +/** + * 画布上的边。 + * + * React Flow 自带的 smoothstep 把竖直段一律摆在源和目标的正中间,同一列的 + * 边就会全部重合。路径改由 `routing.ts` 统一算(端口错开 + 走廊车道), + * 这里只负责画。 + * + * 拿不到路径时(还没量到节点尺寸、边指向了不存在的节点)退回自带的 + * smoothstep——宁可难看一帧,也不要线消失。 + */ +export function FlowEdge({ + id, sourceX, sourceY, targetX, targetY, sourcePosition, targetPosition, + label, labelStyle, markerEnd, markerStart, interactionWidth, style, +}: EdgeProps) { + const routes = useContext(RoutingContext) + const route = routes?.get(id) + + const [fallback] = getSmoothStepPath({ + sourceX, sourceY, targetX, targetY, sourcePosition, targetPosition, + }) + const path = route?.path || fallback + + return ( + <> + + {label != null && label !== '' && ( + +
+ {label} +
+
+ )} + + ) +} diff --git a/frontend/src/canvas/NodeCard.tsx b/frontend/src/canvas/NodeCard.tsx index b68b61f4..a20b54c8 100644 --- a/frontend/src/canvas/NodeCard.tsx +++ b/frontend/src/canvas/NodeCard.tsx @@ -3,6 +3,7 @@ import { Handle, Position, type NodeProps } from '@xyflow/react' import { AlertTriangle, Check, Hand, Loader2, Sparkles, Wrench } from 'lucide-react' import clsx from 'clsx' import { NODE_DEFS, sourceHandles } from './nodeDefs' +import { NODE_WIDTH } from './routing' import { formatDuration } from '../run/decode' import { useStudio, type FlowNode } from '../store/studio' import type { NodeType } from '../types' @@ -78,7 +79,7 @@ function NodeCardImpl({ id, data, selected }: NodeProps) { copilotNew && 'node-copilot-new', selected && 'ring-2 ring-[var(--accent)] ring-offset-1 ring-offset-[var(--bg)]', )} - style={{ width: 238, borderColor: selected ? 'var(--accent)' : undefined }} + style={{ width: NODE_WIDTH, borderColor: selected ? 'var(--accent)' : undefined }} > {def?.hasTarget && ( diff --git a/frontend/src/canvas/routing.ts b/frontend/src/canvas/routing.ts new file mode 100644 index 00000000..188a4980 --- /dev/null +++ b/frontend/src/canvas/routing.ts @@ -0,0 +1,502 @@ +/** + * 画布的连线走线。 + * + * 背景:以前所有边都交给 React Flow 的 smoothstep,它的竖直段一律落在 + * 源和目标的正中间。于是同一列的边全都挤在同一个 x 上:一个节点扇出三条, + * 三条线的竖段完全重合;两条边汇进同一个节点,末段又重合。看上去就是 + * 一团线糊在一起,分不清哪条连到哪。 + * + * 这里的做法是给每条线安排自己的车道: + * + * 1. **端口**:一个节点的多条出边沿它的右边缘错开,多条入边沿左边缘错开。 + * 线不再从同一个点出发、也不在同一个点结束。入边的顺序按上游的纵向 + * 位置排,所以同一列里的线不会互相交叉。 + * 2. **走廊与车道**:相邻两列之间是一条走廊,走廊里竖直走线按区间染色 + * 分配车道——竖直区间真的叠在一起的才各占一条,首尾相接的(同一个扇出 + * 点)共用一条,看起来就是一条总线,而不是硬生生拆成三条平行线。 + * 3. **长边与回边**:跨多列的长边不走直线穿堂,而是找一条横向上没有节点的 + * 空档绕过去;循环的回边同样从图的上方或下方兜一圈。 + * + * 走廊宽度由后端 `engine/layout.py` 按车道数预留,两边算车道用的是同一套 + * 贪心(见 `_lane_count`),所以留出来的宽度够用。 + */ + +import { sourceHandles, type HandleDef } from './nodeDefs' +import type { NodeType } from '../types' + +/** 节点宽度。NodeCard 里写死的 `width: 238`,两边必须一致。 */ +export const NODE_WIDTH = 238 +/** 端口在节点边缘外的偏移。和 NodeCard 里 Handle 的 `right/left: -5` 对齐。 */ +const SOURCE_PORT_DX = 5 +const TARGET_PORT_DX = -5 +/** 竖直车道间距,与 layout.py 的 LANE 一致。 */ +const LANE = 18 +/** 连线离开节点后至少先走这么远再拐弯。 */ +const STUB = 14 +/** 圆角半径。 */ +const RADIUS = 8 +/** 竖直区间重叠多少以内算同一条道(和 layout.py 的 TOLERANCE 对齐)。 */ +const LANE_TOLERANCE = 6 +/** 绕行时离节点框至少留的空隙。 */ +const BAND_PAD = 12 +/** 两列的中心距离小于它就算同一列。用户手拖过的节点不至于被拆成两列。 */ +const COLUMN_TOLERANCE = 60 + +export interface Point { + x: number + y: number +} + +export interface Route { + path: string + labelX: number + labelY: number +} + +/** buildRoutes 需要的节点信息,结构上就是 store 里的 FlowNode。 */ +export interface RouteNodeLike { + id: string + position: { x: number; y: number } + measured?: { width?: number; height?: number } + data: { nodeType: NodeType; config: Record } +} + +export interface RouteEdgeLike { + id: string + source: string + target: string + sourceHandle?: string | null +} + +interface Geometry { + id: string + x: number + y: number + width: number + height: number + centerY: number + right: number + left: number + bottom: number + nodeType: NodeType + config: Record + handles: HandleDef[] +} + +interface Column { + left: number + right: number + /** 列里最大的节点 x,用来判断下一个节点还算不算这一列 */ + lastX: number + members: Geometry[] +} + +interface Segment { + edgeId: string + start: number + end: number + lane: number +} + +/** 端口在一组边里的纵向偏移。一条边时就是原位,多了才错开。 */ +function spreadOffsets(count: number, height: number): number[] { + if (count <= 1) return [0] + const spacing = Math.max(7, Math.min(14, (height - 34) / (count - 1))) + const total = spacing * (count - 1) + return Array.from({ length: count }, (_, i) => -total / 2 + i * spacing) +} + +function toGeometry(node: RouteNodeLike): Geometry { + // 用 || 而不是 ??:React Flow 还没量到尺寸时会先给 0,那会把端口算到 + // 节点外面去。宁可退回写死的默认值。 + const width = node.measured?.width || NODE_WIDTH + const height = node.measured?.height || 74 + const x = node.position.x + const y = node.position.y + return { + id: node.id, + x, + y, + width, + height, + centerY: y + height / 2, + right: x + width, + left: x, + bottom: y + height, + nodeType: node.data.nodeType, + config: node.data.config ?? {}, + handles: sourceHandles(node.data.nodeType, node.data.config ?? {}), + } +} + +/** + * 出口的纵向位置。多出口的节点(branch / loop / human)每个出口在卡片右侧 + * 各有各的位置,单出口的节点所有出边共用一个点——和 NodeCard 画 Handle 的 + * 算式必须一致,不然线会从卡片外面接进来。 + */ +function handleBaseY(node: Geometry, handleId: string): number { + const handles = node.handles + if (handles.length <= 1) return node.centerY + const index = Math.max(0, handles.findIndex((h) => h.id === handleId)) + return node.y + (node.height * (index + 1)) / (handles.length + 1) +} + +function resolveHandleId(node: Geometry, raw?: string | null): string { + if (raw && node.handles.some((h) => h.id === raw)) return raw + return node.handles[0]?.id ?? 'out' +} + +/** 合并靠得太近的 x,得到"列"。用户随手拖过的节点不该被当成新的一列。 */ +function buildColumns(geoms: Geometry[]): { columns: Column[]; colOf: Map } { + const columns: Column[] = [] + const colOf = new Map() + for (const g of [...geoms].sort((a, b) => a.x - b.x)) { + const last = columns[columns.length - 1] + if (last && g.x - last.lastX < COLUMN_TOLERANCE) { + last.right = Math.max(last.right, g.right) + last.left = Math.min(last.left, g.left) + last.lastX = Math.max(last.lastX, g.x) + last.members.push(g) + } else { + columns.push({ left: g.left, right: g.right, lastX: g.x, members: [g] }) + } + colOf.set(g.id, columns.length - 1) + } + return { columns, colOf } +} + +/** + * 走廊里的车道分配:按起点排序做首次适应染色。 + * + * 竖直区间真的叠在一起才换道;首尾相接(同一个扇出点的三条线)共用一条, + * 这样扇出看起来是一条总线,而不是三条贴在一起的平行线。 + */ +function assignLanes(segments: Segment[]): number { + const lanes: number[] = [] + for (const seg of [...segments].sort((a, b) => a.start - b.start)) { + let placed = -1 + for (let i = 0; i < lanes.length; i++) { + if (seg.start >= lanes[i] - LANE_TOLERANCE) { + lanes[i] = Math.max(lanes[i], seg.end) + placed = i + break + } + } + if (placed < 0) { + lanes.push(seg.end) + placed = lanes.length - 1 + } + seg.lane = placed + } + return lanes.length +} + +/** 车道在走廊里的 x。整束车道居中,走廊窄的时候自动压缩间距。 */ +function laneX(column: Column, next: Column, lane: number, total: number): number { + const left = column.right + const avail = Math.max(0, next.left - left) + if (total <= 1) return left + avail / 2 + const gap = Math.max(6, Math.min(LANE, (avail - STUB * 2) / (total - 1))) + const span = gap * (total - 1) + return left + (avail - span) / 2 + lane * gap +} + +/** + * 找一条横着穿过去不会撞到节点的空档。 + * + * 长边如果直接从源的高度平推过去,会横穿中间那些列的卡片——这正是以前 + * 画布上最难看的地方。所以在中间各列的纵向占用里找空隙,挑离理想高度最近 + * 的那条走。 + */ +function freeBand( + columns: Column[], from: number, to: number, ideal: number, used: number[], +): number { + const lo = Math.min(from, to) + const hi = Math.max(from, to) + const occupied: [number, number][] = [] + for (let c = lo; c <= hi; c++) { + for (const g of columns[c]?.members ?? []) { + occupied.push([g.y - BAND_PAD, g.bottom + BAND_PAD]) + } + } + occupied.sort((a, b) => a[0] - b[0]) + const merged: [number, number][] = [] + for (const iv of occupied) { + const last = merged[merged.length - 1] + if (last && iv[0] <= last[1]) last[1] = Math.max(last[1], iv[1]) + else merged.push([iv[0], iv[1]]) + } + + const gaps: [number, number][] = [] + let cursor = (merged[0]?.[0] ?? ideal) - 260 + for (const iv of merged) { + gaps.push([cursor, iv[0]]) + cursor = Math.max(cursor, iv[1]) + } + gaps.push([cursor, cursor + 260]) + + const pick = (y: number): number | null => { + for (const [g0, g1] of gaps) { + if (g1 - g0 < 24) continue + if (y >= g0 + BAND_PAD && y <= g1 - BAND_PAD) return y + } + return null + } + + // 从理想高度出发,先在最近的空档里找位置;和别的绕行线撞了就顺着空档挪开 + const candidates = [ideal] + for (let step = 1; step <= 6; step++) { + candidates.push(ideal + step * 22, ideal - step * 22) + } + for (const y of candidates) { + const spot = pick(y) + if (spot === null) continue + if (used.every((u) => Math.abs(u - spot) >= 16)) return spot + } + for (const y of candidates) { + const spot = pick(y) + if (spot !== null) return spot + } + return ideal +} + +/** 把折线画成带圆角的路径。 */ +function roundedPath(points: Point[]): string { + const pts: Point[] = [] + for (const p of points) { + const last = pts[pts.length - 1] + if (!last || Math.abs(last.x - p.x) > 0.5 || Math.abs(last.y - p.y) > 0.5) pts.push(p) + } + if (pts.length < 2) return '' + let d = `M${pts[0].x} ${pts[0].y}` + for (let i = 1; i < pts.length - 1; i++) { + const prev = pts[i - 1] + const cur = pts[i] + const next = pts[i + 1] + const inLen = Math.hypot(cur.x - prev.x, cur.y - prev.y) + const outLen = Math.hypot(next.x - cur.x, next.y - cur.y) + const r = Math.min(RADIUS, inLen / 2, outLen / 2) + if (r < 0.5) { + d += `L${cur.x} ${cur.y}` + continue + } + const a = { + x: cur.x - ((cur.x - prev.x) / inLen) * r, + y: cur.y - ((cur.y - prev.y) / inLen) * r, + } + const b = { + x: cur.x + ((next.x - cur.x) / outLen) * r, + y: cur.y + ((next.y - cur.y) / outLen) * r, + } + d += `L${a.x} ${a.y}Q${cur.x} ${cur.y} ${b.x} ${b.y}` + } + const last = pts[pts.length - 1] + d += `L${last.x} ${last.y}` + return d +} + +/** 折线中点,标签摆这儿。 */ +function polylineMidpoint(points: Point[]): Point { + const lengths: number[] = [] + let total = 0 + for (let i = 1; i < points.length; i++) { + const len = Math.hypot(points[i].x - points[i - 1].x, points[i].y - points[i - 1].y) + lengths.push(len) + total += len + } + if (total === 0) return points[0] + let target = total / 2 + for (let i = 0; i < lengths.length; i++) { + if (target <= lengths[i]) { + const t = lengths[i] === 0 ? 0 : target / lengths[i] + return { + x: points[i].x + (points[i + 1].x - points[i].x) * t, + y: points[i].y + (points[i + 1].y - points[i].y) * t, + } + } + target -= lengths[i] + } + return points[points.length - 1] +} + +export function buildRoutes( + nodes: RouteNodeLike[], edges: RouteEdgeLike[], +): Map { + const geoms = nodes.map(toGeometry) + const byId = new Map(geoms.map((g) => [g.id, g])) + const routes = new Map() + if (!geoms.length) return routes + + const { columns, colOf } = buildColumns(geoms) + + // ---- 1. 端口:出边沿右边缘错开,入边沿左边缘错开 ---- + const sourceY = new Map() + const outGroups = new Map() + const inGroups = new Map() + for (const e of edges) { + const source = byId.get(e.source) + const target = byId.get(e.target) + if (!source || !target) continue + const key = `${e.source}\u0000${resolveHandleId(source, e.sourceHandle)}` + outGroups.set(key, [...(outGroups.get(key) ?? []), e]) + inGroups.set(e.target, [...(inGroups.get(e.target) ?? []), e]) + } + + for (const [key, group] of outGroups) { + const [nodeId, handleId] = key.split('\u0000') + const node = byId.get(nodeId)! + const base = handleBaseY(node, handleId) + // 同一条出边上,目标在上面的先出去——扇出的顺序才不会交叉 + const ordered = [...group].sort((a, b) => { + const ta = byId.get(a.target)! + const tb = byId.get(b.target)! + return ta.centerY - tb.centerY || a.target.localeCompare(b.target) + }) + const offsets = spreadOffsets(ordered.length, node.height) + ordered.forEach((e, i) => sourceY.set(e.id, base + offsets[i])) + } + + const targetY = new Map() + for (const [nodeId, group] of inGroups) { + const node = byId.get(nodeId)! + const ordered = [...group].sort((a, b) => { + const sa = sourceY.get(a.id) ?? byId.get(a.source)!.centerY + const sb = sourceY.get(b.id) ?? byId.get(b.source)!.centerY + return sa - sb || a.source.localeCompare(b.source) + }) + const offsets = spreadOffsets(ordered.length, node.height) + ordered.forEach((e, i) => targetY.set(e.id, node.centerY + offsets[i])) + } + + // ---- 2. 分类 + 绕行高度 ---- + interface Plan { + edge: RouteEdgeLike + kind: 'short' | 'long' | 'back' | 'self' + colS: number + colT: number + sx: number + sy: number + tx: number + ty: number + band: number + } + const plans: Plan[] = [] + const usedBands: number[] = [] + // 先算跨得最远的边:它们的绕行高度要避开彼此 + const bySpan = [...edges].sort((a, b) => { + const ca = Math.abs((colOf.get(a.target) ?? 0) - (colOf.get(a.source) ?? 0)) + const cb = Math.abs((colOf.get(b.target) ?? 0) - (colOf.get(b.source) ?? 0)) + return cb - ca + }) + for (const e of bySpan) { + const source = byId.get(e.source) + const target = byId.get(e.target) + if (!source || !target) continue + const colS = colOf.get(e.source)! + const colT = colOf.get(e.target)! + const sy = sourceY.get(e.id) ?? source.centerY + const ty = targetY.get(e.id) ?? target.centerY + const kind: Plan['kind'] = + e.source === e.target ? 'self' + : colT === colS ? 'self' + : colT < colS ? 'back' + : colT === colS + 1 ? 'short' : 'long' + const ideal = (sy + ty) / 2 + let band = 0 + if (kind === 'long' || kind === 'back') { + // 横着穿过去的那一段到底压过哪几列:长边从源列右侧出发、停在目标列 + // 左侧的车道里,压到的是中间那几列;回边往左走,连源列和目标列一起压。 + // 算准了才不会为了躲开根本没压到的卡片,白白绕一大圈。 + const from = kind === 'long' ? colS + 1 : colT + const to = kind === 'long' ? colT - 1 : colS + band = freeBand(columns, from, to, ideal, usedBands) + usedBands.push(band) + } + plans.push({ + edge: e, kind, colS, colT, + sx: source.right + SOURCE_PORT_DX, sy, + tx: target.left + TARGET_PORT_DX, ty, + band, + }) + } + + // ---- 3. 车道:每条竖直段登记到它所在的走廊 ---- + const corridorSegments = new Map() + const push = (corridor: number, edgeId: string, start: number, end: number) => { + if (corridor < 0 || corridor >= columns.length - 1) return + corridorSegments.set(corridor, [ + ...(corridorSegments.get(corridor) ?? []), + { edgeId, start: Math.min(start, end), end: Math.max(start, end), lane: 0 }, + ]) + } + for (const plan of plans) { + if (plan.kind === 'short') { + push(plan.colS, plan.edge.id, plan.sy, plan.ty) + } else if (plan.kind === 'long' || plan.kind === 'back') { + push(plan.colS, plan.edge.id, plan.sy, plan.band) + push(plan.colT - 1, plan.edge.id, plan.band, plan.ty) + } + } + const corridorLanes = new Map() + const laneOf = new Map() + for (const [corridor, segments] of corridorSegments) { + const total = assignLanes(segments) + corridorLanes.set(corridor, total) + for (const seg of segments) laneOf.set(`${seg.edgeId}\u0000${corridor}`, seg.lane) + } + + const laneAt = (corridor: number, edgeId: string): number | null => { + if (corridor < 0 || corridor >= columns.length - 1) return null + const lane = laneOf.get(`${edgeId}\u0000${corridor}`) ?? 0 + return laneX(columns[corridor], columns[corridor + 1], lane, corridorLanes.get(corridor) ?? 1) + } + + // ---- 4. 出路径 ---- + for (const plan of plans) { + let points: Point[] + if (plan.kind === 'short') { + const x = laneAt(plan.colS, plan.edge.id) ?? (plan.sx + plan.tx) / 2 + points = [ + { x: plan.sx, y: plan.sy }, + { x, y: plan.sy }, + { x, y: plan.ty }, + { x: plan.tx, y: plan.ty }, + ] + } else if (plan.kind === 'long' || plan.kind === 'back') { + const outX = laneAt(plan.colS, plan.edge.id) + const inX = laneAt(plan.colT - 1, plan.edge.id) + const startX = outX ?? plan.sx + STUB + const endX = inX ?? plan.tx - 26 + points = [ + { x: plan.sx, y: plan.sy }, + { x: startX, y: plan.sy }, + { x: startX, y: plan.band }, + { x: endX, y: plan.band }, + { x: endX, y: plan.ty }, + { x: plan.tx, y: plan.ty }, + ] + } else { + // 自环:贴着卡片右边出去,从下面兜回来 + const node = byId.get(plan.edge.source)! + const outX = node.right + 26 + const inX = node.left - 26 + const band = node.bottom + 34 + points = [ + { x: plan.sx, y: plan.sy }, + { x: outX, y: plan.sy }, + { x: outX, y: band }, + { x: inX, y: band }, + { x: inX, y: plan.ty }, + { x: plan.tx, y: plan.ty }, + ] + } + const mid = polylineMidpoint(points) + routes.set(plan.edge.id, { + path: roundedPath(points), + labelX: mid.x, + labelY: mid.y, + }) + } + + return routes +} diff --git a/frontend/src/store/studio.ts b/frontend/src/store/studio.ts index f9580493..97a07025 100644 --- a/frontend/src/store/studio.ts +++ b/frontend/src/store/studio.ts @@ -39,7 +39,9 @@ export function toFlow(graph: GraphSpec): { nodes: FlowNode[]; edges: Edge[] } { sourceHandle: e.sourceHandle ?? null, targetHandle: e.targetHandle ?? null, label: e.label || undefined, - type: 'smoothstep', + // 走线由 canvas/routing.ts 统一算(端口错开 + 走廊车道), + // 不用自带的 smoothstep:它的竖直段全都落在同一个 x 上,会叠成一团 + type: 'flow', animated: false, })), } @@ -162,6 +164,8 @@ interface StudioState { copilotNew: string[] copilotTurns: CopilotTurn[] cancelCopilot: (() => void) | null + /** 每次 +1 = 请求画布重新取景。整张图换过坐标之后不重新取景,人会盯着一片空白 */ + fitRequest: number // actions load: (workflow: Workflow) => void @@ -269,6 +273,7 @@ export const useStudio = create((set, get) => ({ copilotNew: [], copilotTurns: [], cancelCopilot: null, + fitRequest: 0, load: (workflow) => { const { nodes, edges } = toFlow(workflow.graph) @@ -276,6 +281,9 @@ export const useStudio = create((set, get) => ({ set({ workflow, nodes, edges, selectedId: null, dirty: false, issues: [], run: null, events: [], runtime: {}, activeEdges: [], streaming: false, unsubscribe: null, + // 整张图换了,视角也要跟着换。不换的话打开另一张图看到的还是上一张的 + // 那块空白——画布位置是视口的,不是图的 + fitRequest: get().fitRequest + 1, // 换了一张图,之前那些"我让它改成这样"就不再指向眼前这张图了 copilotTurns: [], // 先清空再去解析:留着上一张图的会话 id,这中间的任何一条指令 @@ -288,7 +296,7 @@ export const useStudio = create((set, get) => ({ setGraph: (graph) => { const { nodes, edges } = toFlow(graph) - set({ nodes, edges, dirty: true }) + set({ nodes, edges, dirty: true, fitRequest: get().fitRequest + 1 }) void get().validate() }, @@ -621,6 +629,9 @@ export const useStudio = create((set, get) => ({ // 后端排版+校验后的最终图整体落位;高亮集合保留几秒供辨认 const { nodes, edges } = toFlow(op.graph) set({ nodes, edges, dirty: true, + // 生成完的图坐标是后端新排的,视角得跟过去,否则"生成好了" + // 这句话落在一片空白上 + fitRequest: get().fitRequest + 1, copilot: { ...get().copilot, active: false, lastOp: '', phase: '', thinking: '', elapsedMs: 0, error: '', explanation: op.explanation ?? get().copilot.explanation } }) diff --git a/scripts/check-canvas-layout.mjs b/scripts/check-canvas-layout.mjs new file mode 100644 index 00000000..e6079917 --- /dev/null +++ b/scripts/check-canvas-layout.mjs @@ -0,0 +1,328 @@ +// 画布排版 + 连线走线的自动检查:真后端排版,真前端走线,然后按几何算。 +// +// 这一层守的是"图好不好看"里唯一能算的那部分:线有没有叠在一起、长边有没有 +// 从卡片中间穿过去、线有没有接在节点外面。check-ui / e2e-check 只看得到 +// "页面没报错、节点在、能点",连线叠成一团它们一个字都不会说。 +// +// 跑之前前端得起着(./scripts/dev.sh),因为走线模块是 Vite 现编的 TS: +// 检查脚本直接 import('/src/canvas/routing.ts'),用的是页面上跑的那份代码, +// 不是抄一遍逻辑——抄一遍就等于只测了抄的那份。 +import { chromium } from '../frontend/node_modules/playwright-core/index.mjs' + +const WEB = process.env.AGENTLAB_WEB ?? 'http://localhost:5273' +const API = process.env.AGENTLAB_API ?? 'http://localhost:8000/api' +const CHROME = process.env.CHROME_PATH + ?? '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome' + +let failed = 0 +const check = (name, cond, detail = '') => { + console.log(` ${cond ? '✓' : '✗'} ${name}${detail ? ` — ${detail}` : ''}`) + if (!cond) failed++ +} + +// ---------------------------------------------------------------- 夹具 + +const node = (id, type, config = {}) => ({ id, type, data: { label: id, config } }) +const edge = (source, target, sourceHandle) => ({ source, target, sourceHandle }) + +/** 三路并行 → 归并 → 分支,再带一条跨层长边 */ +const PARALLEL = { + nodes: [ + node('in', 'input'), node('a1', 'agent'), node('a2', 'agent'), node('a3', 'agent'), + node('m1', 'llm'), node('m2', 'llm'), node('join', 'llm'), + node('gate', 'branch', { cases: [{ key: 'yes' }, { key: 'no' }] }), + node('fix', 'llm'), node('ok', 'output'), node('bad', 'output'), + ], + edges: [ + edge('in', 'a1'), edge('in', 'a2'), edge('in', 'a3'), + edge('a1', 'm1'), edge('a2', 'm1'), edge('a3', 'm2'), + edge('m1', 'join'), edge('m2', 'join'), edge('a3', 'join'), + edge('join', 'gate'), + edge('gate', 'fix', 'no'), edge('gate', 'ok', 'yes'), + edge('fix', 'ok'), edge('fix', 'bad'), + ], +} + +/** 一路扇出 8 条并行支路再全部汇进一个节点:车道压力最大的形状 */ +const WIDE = { + nodes: [node('in', 'input'), node('join', 'llm'), + ...Array.from({ length: 8 }, (_, i) => node(`m${i}`, 'llm'))], + edges: [ + ...Array.from({ length: 8 }, (_, i) => edge('in', `m${i}`)), + ...Array.from({ length: 8 }, (_, i) => edge(`m${i}`, 'join')), + ], +} + +/** 循环:一条回边要从整张图外面兜回去 */ +const LOOP = { + nodes: [ + node('start', 'input'), node('each', 'loop'), node('body', 'llm'), + node('collect', 'transform'), node('done', 'output'), + ], + edges: [ + edge('start', 'each'), edge('each', 'body', 'body'), edge('body', 'collect'), + edge('collect', 'each'), edge('each', 'done', 'done'), + ], +} + +/** 分支的两个出口又汇到同一个节点:入端口错开得对不对就看它 */ +const MERGE_BRANCH = { + nodes: [ + node('start', 'input'), + node('gate', 'branch', { cases: [{ key: 'yes' }, { key: 'no' }] }), + node('left', 'llm'), node('right', 'llm'), node('done', 'output'), + ], + edges: [ + edge('start', 'gate'), edge('gate', 'left', 'yes'), edge('gate', 'right', 'no'), + edge('left', 'done'), edge('right', 'done'), + ], +} + +/** 两个出口直接连到同一个节点:端口错开最极端的情况(起点终点都只差一点) */ +const BOTH_WAYS = { + nodes: [ + node('start', 'input'), + node('gate', 'branch', { cases: [{ key: 'yes' }, { key: 'no' }] }), + node('done', 'output'), + ], + edges: [ + edge('start', 'gate'), edge('gate', 'done', 'yes'), edge('gate', 'done', 'no'), + ], +} + +const FIXTURES = { PARALLEL, WIDE, LOOP, MERGE_BRANCH, BOTH_WAYS } + +// ---------------------------------------------------------------- 几何 + +/** 把 M/L/Q 路径拆成横平竖直的线段。Q 是拐角的圆弧,取端点即可。 */ +function segmentsOf(path) { + const tokens = path.match(/[MLQ][^MLQ]*/g) ?? [] + const points = [] + for (const token of tokens) { + const nums = token.slice(1).trim().split(/[\s,]+/).map(Number) + if (token[0] === 'Q') points.push({ x: nums[2], y: nums[3] }) + else points.push({ x: nums[0], y: nums[1] }) + } + const segments = [] + for (let i = 1; i < points.length; i++) { + const a = points[i - 1] + const b = points[i] + if (Math.abs(a.x - b.x) < 0.6 && Math.abs(a.y - b.y) < 0.6) continue + segments.push({ a, b }) + } + return segments +} + +const isHorizontal = (s) => Math.abs(s.a.y - s.b.y) < 0.6 +const isVertical = (s) => Math.abs(s.a.x - s.b.x) < 0.6 +const span = (s, axis) => { + const lo = Math.min(s.a[axis], s.b[axis]) + const hi = Math.max(s.a[axis], s.b[axis]) + return [lo, hi] +} +const overlapOf = (s1, s2, axis) => { + const [a0, a1] = span(s1, axis) + const [b0, b1] = span(s2, axis) + return Math.min(a1, b1) - Math.max(a0, b0) +} + +/** 两条线段是不是压在同一条线上 */ +function collides(s1, s2) { + if (isHorizontal(s1) && isHorizontal(s2)) { + if (Math.abs(s1.a.y - s2.a.y) > 1) return 0 + return overlapOf(s1, s2, 'x') + } + if (isVertical(s1) && isVertical(s2)) { + if (Math.abs(s1.a.x - s2.a.x) > 1) return 0 + return overlapOf(s1, s2, 'y') + } + return 0 +} + +function boxCrossings(segments, boxes, ownIds) { + const hits = [] + for (const s of segments) { + for (const box of boxes) { + if (ownIds.has(box.id)) continue + const [x0, x1] = span(s, 'x') + const [y0, y1] = span(s, 'y') + const pad = 2 + if (x0 < box.right - pad && x1 > box.left + pad + && y0 < box.bottom - pad && y1 > box.top + pad) { + hits.push(box.id) + } + } + } + return hits +} + +// ---------------------------------------------------------------- 跑 + +const browser = await chromium.launch({ executablePath: CHROME }) +const ctx = await browser.newContext({ viewport: { width: 1280, height: 800 } }) +const page = await ctx.newPage() +const pageErrors = [] +page.on('pageerror', (e) => pageErrors.push(e.message)) +await page.goto(`${WEB}/studio`, { waitUntil: 'networkidle' }) + +// 走线模块是从 dev server 现编现取的。打包产物里没有这个路径,先探一下, +// 免得后面报一句看不懂的 import 失败 +try { + await page.evaluate(async () => { await import('/src/canvas/routing.ts') }) +} catch (e) { + console.error(`拿不到 /src/canvas/routing.ts:这个检查跑在 Vite dev server 上,` + + `先 ./scripts/dev.sh(当前 ${WEB})。${e.message}`) + await browser.close() + process.exit(1) +} + +for (const [name, graph] of Object.entries(FIXTURES)) { + console.log(`=== ${name} ===`) + + const res = await fetch(`${API}/copilot/layout`, { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ graph }), + }) + if (!res.ok) { + check('后端排版可用', false, `${res.status}`) + continue + } + const laid = await res.json() + + const report = await page.evaluate(async ({ graph, laid }) => { + const mod = await import('/src/canvas/routing.ts') + // 节点高度用实测范围里偏大的一档:卡片带摘要、带运行态时会更高, + // 用最小值去检查等于给自己放水 + const heights = [74, 92, 108] + const nodes = laid.nodes.map((n, i) => ({ + id: n.id, + position: n.position, + measured: { width: 238, height: heights[i % heights.length] }, + data: { nodeType: n.type, config: n.data?.config ?? {} }, + })) + const routes = mod.buildRoutes(nodes, laid.edges.map((e, i) => ({ + id: e.id || `e${i}`, source: e.source, target: e.target, + sourceHandle: e.sourceHandle ?? null, + }))) + const out = [] + for (const [id, route] of routes) out.push({ id, path: route.path }) + return out + }, { graph, laid }) + + const boxes = laid.nodes.map((n) => ({ + id: n.id, + left: n.position.x, + right: n.position.x + 238, + top: n.position.y, + bottom: n.position.y + 108, + })) + + check('每条边都算出了路径', report.length === laid.edges.length, + `${report.length}/${laid.edges.length}`) + + const segments = new Map() + for (const item of report) segments.set(item.id, segmentsOf(item.path)) + + // 1. 不同边之间不能有压在一起的线段 + const overlaps = [] + const ids = [...segments.keys()] + for (let i = 0; i < ids.length; i++) { + for (let j = i + 1; j < ids.length; j++) { + for (const s1 of segments.get(ids[i])) { + for (const s2 of segments.get(ids[j])) { + if (collides(s1, s2) > 2) overlaps.push(`${ids[i]} × ${ids[j]}`) + } + } + } + } + check('没有两条线压在同一段上', overlaps.length === 0, + overlaps.slice(0, 4).join('、')) + + // 2. 长边不能从别的卡片中间穿过去 + const crossings = [] + for (const item of report) { + const e = laid.edges.find((x, i) => (x.id || `e${i}`) === item.id) ?? {} + const hits = boxCrossings(segments.get(item.id), boxes, new Set([e.source, e.target])) + if (hits.length) crossings.push(`${item.id}→${[...new Set(hits)].join(',')}`) + } + check('没有线穿过别人的卡片', crossings.length === 0, crossings.slice(0, 3).join('、')) + + // 3. 起点终点要落在节点边缘上(差一点没关系,掉在节点里或图外面就是错的) + const byId = new Map(laid.nodes.map((n) => [n.id, n])) + const dangling = [] + for (const item of report) { + const e = laid.edges.find((x, i) => (x.id || `e${i}`) === item.id) + if (!e) continue + const segs = segments.get(item.id) + if (!segs.length) continue + const start = segs[0].a + const end = segs[segs.length - 1].b + const src = byId.get(e.source) + const dst = byId.get(e.target) + if (Math.abs(start.x - (src.position.x + 238)) > 12) { + dangling.push(`${item.id} 起点 x=${start.x.toFixed(0)}`) + } + if (Math.abs(end.x - dst.position.x) > 12) { + dangling.push(`${item.id} 终点 x=${end.x.toFixed(0)}`) + } + } + check('每条线的两端都接在节点上', dangling.length === 0, dangling.slice(0, 3).join('、')) +} + +check('页面没有运行时错误', pageErrors.length === 0, pageErrors.join(' | ')) + +// 手拖过的节点位置是随机的:坐标乱七八糟时不能算出 NaN 路径。 +// NaN 的 path 什么都不画,界面上就是"线没了",而且一声不吭。 +console.log('=== 随机坐标(手拖过的图) ===') +{ + const fuzz = await page.evaluate(async () => { + const mod = await import('/src/canvas/routing.ts') + let seed = 20240924 + const rnd = () => (seed = (seed * 1103515245 + 12345) % 2147483648) / 2147483648 + const types = ['input', 'llm', 'agent', 'branch', 'loop', 'output', 'human', 'transform'] + let total = 0 + let broken = 0 + const examples = [] + for (let trial = 0; trial < 200; trial++) { + const n = 3 + Math.floor(rnd() * 9) + const nodes = Array.from({ length: n }, (_, i) => ({ + id: `n${i}`, + position: { x: Math.round(rnd() * 1800) - 200, y: Math.round(rnd() * 900) - 300 }, + measured: { width: 238, height: 40 + Math.round(rnd() * 90) }, + data: { + nodeType: types[Math.floor(rnd() * types.length)], + config: { cases: [{ key: 'yes' }, { key: 'no' }] }, + }, + })) + const edges = [] + for (let i = 0; i < n; i++) { + for (let k = 0, m = Math.floor(rnd() * 3); k < m; k++) { + edges.push({ + id: `e${i}_${k}`, source: `n${i}`, + target: `n${Math.floor(rnd() * n)}`, + sourceHandle: rnd() < 0.4 ? 'yes' : null, + }) + } + } + const routes = mod.buildRoutes(nodes, edges) + for (const e of edges) { + total++ + const route = routes.get(e.id) + const ok = route && route.path.length >= 4 && !/NaN|Infinity|undefined/.test(route.path) + && Number.isFinite(route.labelX) && Number.isFinite(route.labelY) + if (!ok) { + broken++ + if (examples.length < 3) examples.push(`${e.id}: ${route?.path?.slice(0, 60)}`) + } + } + } + return { total, broken, examples } + }) + check(`随机坐标下每条边都画得出来(${fuzz.total} 条)`, fuzz.broken === 0, + fuzz.examples.join('、')) +} + +console.log(failed ? `\n${failed} 项未通过` : '\n全部通过') +await browser.close() +process.exit(failed ? 1 : 0)