fix: harden CLI parsing, MCP startup and release integrity

This commit is contained in:
gitea committed 2026-10-17 20:32:36 +08:00
1 parent f0902f5f20
commit 103ead0fe5
53 files changed
+3713 -1945

No files matched your search

@@ -0,0 +1,74 @@
# Workflow 工作流模块
Platform 域下工作流能力的命令、协议与诊断契约。总体边界见 [Platform 概览](../README.platform.md)。
## CLI 常用命令
```bash
hose-use workflow list [--platform-id=<id>|--app-id=<id>]
hose-use workflow get <pipelineId>
hose-use workflow enum [thirdId] [--third-id=<id>] [--json]
hose-use workflow analyze <pipelineId> [--json]
hose-use workflow logs <pipelineId> [--has-error] [--state=FAILED]
hose-use workflow job <jobId> [--failed] [--node=<name|id>] [--verbose]
hose-use workflow diff <snapshotId1> <snapshotId2> [--pipelineId=<id>]
hose-use workflow diff-job <jobId1> <jobId2> [--json]
hose-use workflow test <pipelineId> [--flow=<单号>] [--record=<ID>] [--body='{...}'] [--dry-run|--yes]
hose-use workflow debug <pipelineId> --flow=<单号> --yes
hose-use workflow create [--name=<名称>] [--trigger=webhook|clock|datalink|flowform] [--file=<JSON模板>] [--dry-run|--yes]
hose-use workflow copy <pipelineId> [--name=<名称>] [--platform-id=<应用ID>] [--dry-run|--yes]
hose-use workflow delete <pipelineId> [--dry-run|--yes]
hose-use workflow node list <pipelineId>
hose-use workflow node get <pipelineId> <节点name或#序号>
hose-use workflow node add <pipelineId> --type=code-js2 --label="清洗" --code="..." [--after=<节点>] [--parent=<容器>] [--dry-run|--yes]
hose-use workflow node edit <pipelineId> <节点name或#序号> --label="新标题" [--code="..."] [--dry-run|--yes]
hose-use workflow node rm <pipelineId> <节点name或#序号> [--dry-run|--yes]
hose-use workflow tail <pipelineId> [--job=<jobId>] [--once] [--failed-only] [--interval=2] [--json]
hose-use workflow lint-script <pipelineId> [节点标识] [--json]
hose-use workflow lint-script --code="<code>" [--type=code-js2|code]
hose-use workflow eval-script <pipelineId> <节点标识> [--input='{...}'] [--sample=1] [--timeout=3000]
hose-use workflow eval-script --code="return a + b;" --input='{"a":1,"b":2}'
```
## 触发器分类与调测路径分支 (Path Branching)
合思 EASO/Piper 调度引擎下不同首节点(Trigger)底层的调试协议存在显著差异,`hose-use workflow test` 会自动自适应路由:
| 触发器分类 (`category`) | 常见触发器类型 (`type`) | 调测协议与入参 | CLI 命令与交互行为 |
|---|---|---|---|
| **`SCHEDULE`** (定时调度) | `clock` | 服务端无 `debugSource`,`inputs: { id: "" }` | **自动模拟触发**:无需 `--flow`,直接秒级派发并抓取执行树 |
| **`WEBHOOK`** (外部集成) | `webhook`, `hab-trigger-task`, `xrxs-trigger`, `fxiaoke-trigger` | 服务端维护最近 3 条 Sample 样本 (`/sampleData`),`inputs: { data: { ... } }` | **样本复用与 Payload 注入**:展示参数定义映射 (Key->Label),支持 `--sample=<1\|2\|3>` 直接使用历史真实样本,或 `--body='{...}'` / `--empty` |
| **`DATALINK`** (业务对象台账) | `ekuaibao-datalink-*-trigger` | 服务端返回 `fields` 动态列定义与台账记录 | **动态列展示**:按实体结构动态打表,支持 `--record=<ID>` 或 `--flow=<编码>` |
| **`FLOW_FORM`** (单据流转) | `ekuaibao-flowform-trigger`, `ekuaibao-ebot-trigger` | 服务端返回单据列表与表单定义 | **单据列表与筛选**:支持 `--flow=<单号>`,未提供时拉取候选单据表供挑选 |
## 生产环境调试缺陷与安全防线(合思平台缺陷记录)
> [!WARNING] **合思后端架构缺陷:前端置灰防御,后端裸奔无防**
> 1. **前端置灰表象**:合思 Web 控制台在工作流处于【启用中】(`state = 1`)时,会将【调试】与【保存更新】按钮置灰(disabled),给人以“生产启用态无法调试”的假象;
> 2. **后端无状态鉴权**:合思 EASO/Piper 调度引擎后端 `POST /api/easo/jobs` 接口**完全未对工作流启用状态进行校验**,只要调用 API 即可在生产环境直接派发调试任务;
> 3. **隐蔽快照自增污染**:每次调用 `POST /api/easo/jobs` 调试,服务端均会隐式创建一个新的 Pipeline Snapshot,并将版本号自增(如 `v26.10.10` ➔ `v26.10.13`),无声息地污染发布历史;
> 4. **真实破坏性副作用风险**:合思后端**不具备调试沙箱(Sandbox)隔离**,调试是以真实操作员身份在生产环境真实运行。若下游包含单据自动审批、外部 HTTP 请求、修改业务对象台账或短信通知节点,一旦条件命中,将产生**不可逆的真实生产变更**!
### `hose-use` 生产环境调试特性与全方位风险提示
在合思 Web 控制台中,已发布启用的工作流【调试】按钮被置灰,人工无法直接发起测试;
`hose-use` **保留了穿透前端限制的直达调测能力**(为线上排障与即时验证多保留了一条宝贵的高级通道),但同时提供**充分的安全提示与风险告知**:
- **候选单据提示**:在拉取调试候选数据源时,高亮提示当前工作流处于【🟢 生产启用中】;
- **调试执行提示**:在发起端到端调试时,置顶打印醒目的【生产启用态调试安全提醒】,提醒操作者合思无沙箱、写节点会真实生效以及快照版本会自增,确保线上调测“有路径、知风险、审慎用”。
## 详细文档
完整接口说明、认证链路、MCP tool 列表见:
[docs/modules/platform.md](../../../../docs/modules/platform.md)
## 调试与诊断结果契约
- 调试属于写操作:`--dry-run` 仅展示目标、发布选项和风险,不创建客户端或发起 Job;实际执行需要 `--yes` / `--confirm`。启用中的工作流仍可在确认后直接调试。
- JSON 和预览均包含风险信息。执行结果提供 `productionEnabled`(状态未知时为 `null`)和 `warnings`。
- `outcome` 为 `completed`、`failed`、`timed_out` 或 `incomplete`;只有完整成功才返回退出码 `0`。超时不取消已经发起的 Job,保留 `jobId` 以供 `workflow job` 续查。
- `timedOut`、`diagnosticsComplete`、`diagnosticsErrors` 区分执行超时、读取失败与没有失败节点;权限错误不再被当成空的成功结果。
- 条件解释支持已声明的比较操作符、嵌套 AND/OR 和循环上下文;缺少证据、不支持的值类型或执行尚未结束时,`evaluation` / `matched` 为 `null`,不据此声称分支判定为 False。
- `diff-job` 按父任务路径、循环路径及重复次数配对实例;JSON 节点包含 `instanceKey` / `currentLoopPath`,输出变化也计入差异。
- `execution-context.ts` 是条件解释和 Job diff 共用的纯执行实例索引,不负责请求或 CLI 输出。
@@ -0,0 +1,168 @@
import { describe, expect, it } from "bun:test";
import { analyzeWorkflow } from "./index.js";
import { PlatformSchema } from "../../types.js";
describe("Workflow static analysis", () => {
it("accepts nullable app center metadata", () => {
const platform = PlatformSchema.parse({ id: "app-1", name: "测试应用", corporationId: "corp-1", adminIds: null, importMethod: null });
expect(platform.adminIds).toEqual([]);
expect(platform.importMethod).toEqual([]);
});
it("builds a recursive AST and extracts code references", () => {
const result = analyzeWorkflow({ id: "wf-1", label: "审批", state: 1, version: "3", tasks: [{ name: "条件", type: "condition", label: "条件", groupName: "", orderIndex: 0, levelIndex: [0], status: "", tasks: [{ name: "脚本", type: "code-js2", label: "脚本", groupName: "", orderIndex: 1, levelIndex: [0, 0], status: "", code: "return {{bill.amount}} + ctx.user.id;" }] }] } as any);
expect(result.ast[0]?.children[0]?.path).toBe("0.0"); expect(result.dependencies[0]?.references).toEqual(["bill.amount", "user.id"]); expect(result.diagnostics).toHaveLength(0);
});
it("reports empty scripts, branches, and disabled workflow state", () => {
const result = analyzeWorkflow({ id: "wf-2", label: "异常", state: 0, version: "", tasks: [{ name: "脚本", type: "code", label: "", groupName: "", orderIndex: 0, levelIndex: [0], status: "", code: "" }, { name: "条件", type: "condition", label: "", groupName: "", orderIndex: 1, levelIndex: [1], status: "", tasks: [] }] } as any);
expect(result.diagnostics.map((item) => item.code)).toEqual(["WORKFLOW_DISABLED", "EMPTY_CODE", "EMPTY_BRANCH"]);
});
it("detects UNSAFE_SKIP_WITHOUT_STATUS_GUARD and LINKAGE_PRIORITY_OVERRIDE", () => {
const wf = {
id: "886351399301758976",
label: "【生产】每30分钟创建采购申请单",
state: 1,
version: "10",
tasks: [
{
name: "every_0",
type: "every",
label: "循环每条支付计划",
groupName: "control",
orderIndex: 1,
levelIndex: [0],
status: "",
tasks: [
{
name: "ekuaibao_flow_create_task_0",
type: "flow-create-task",
label: "创建预付申请单",
groupName: "ekuaibao",
orderIndex: 0,
levelIndex: [0, 0],
status: "",
onError: { defaultAction: "SKIP" },
inputs: {
specificationId: "ID01TxgE3fhD6n",
form: {
u_关联合同流程: "{{every_0.item.E_contract}}",
u_我方签约主体: "{{every_0.item.E_company}}",
},
},
},
{
name: "ekuaibao_datalink_edit_0",
type: "ekuaibao-datalink-edit",
label: "更新支付计划状态为创建成功",
groupName: "ekuaibao",
orderIndex: 1,
levelIndex: [0, 1],
status: "",
inputs: {
dataLinkId: "{{every_0.item.id}}",
form: {
状态: "创建成功",
},
},
},
],
},
],
};
const specifications = {
ID01TxgE3fhD6n: {
id: "ID01TxgE3fhD6n",
name: "预付申请单",
form: [
{
id: "f1",
name: "u_关联合同流程",
label: "关联合同流程",
type: "dataLink",
optional: false,
entityId: "e23d0d5451b1ccabfd7a",
assignmentRule: "ID01TRWvYFAulh",
isLinkageAssignment: false,
priorityList: [
{ type: "LINKAGE_ASSIGNMENT", priority: 10 },
{ type: "MANUALLY_FILL_IN", priority: 5 },
],
},
{
id: "f2",
name: "u_我方签约主体",
label: "我方签约主体",
type: "dimension",
optional: false,
isLinkageAssignment: true,
priorityList: [
{ type: "LINKAGE_ASSIGNMENT", priority: 10 },
{ type: "MANUALLY_FILL_IN", priority: 5 },
],
},
],
},
};
const result = analyzeWorkflow(wf as any, { specifications: specifications as any });
const codes = result.diagnostics.map((d) => d.code);
expect(codes).toContain("UNSAFE_SKIP_WITHOUT_STATUS_GUARD");
expect(codes).toContain("LINKAGE_PRIORITY_OVERRIDE");
});
it("detects DEADLOCK_TRIGGER_STATE_FILTER when trigger specifies state APPROVING", () => {
const wf = {
id: "wf-trigger-deadlock",
label: "资金调拨自动审批",
state: 1,
version: "1",
tasks: [
{
name: "trigger_1",
type: "ekuaibao-flowform-trigger",
label: "单据审批事件触发器",
combineFilters: {
filters: [
{
filters: [
{ key: "formSpecification", value: "ID01RUq5zrhZTh", compare: "eq" },
{ key: "state", value: "APPROVING", compare: "eq" },
],
condition: "and",
},
],
condition: "or",
},
},
],
};
const result = analyzeWorkflow(wf as any);
const codes = result.diagnostics.map((d) => d.code);
expect(codes).toContain("DEADLOCK_TRIGGER_STATE_FILTER");
expect(result.diagnostics.find((d) => d.code === "DEADLOCK_TRIGGER_STATE_FILTER")?.severity).toBe("error");
});
it("detects MISSING_BACKLOG_DATA_BRACKETS on backlog openapi http task", () => {
const wf = {
id: "wf-http-no-brackets",
label: "自动审批",
state: 1,
version: "1",
tasks: [
{
name: "action_1",
type: "http",
label: "审批接口调用",
url: "https://app.ekuaibao.com/api/openapi/v1/backlog/data/ID01X4mbLfjvpt",
},
],
};
const result = analyzeWorkflow(wf as any);
const codes = result.diagnostics.map((d) => d.code);
expect(codes).toContain("MISSING_BACKLOG_DATA_BRACKETS");
expect(result.diagnostics.find((d) => d.code === "MISSING_BACKLOG_DATA_BRACKETS")?.severity).toBe("warning");
});
});
@@ -0,0 +1,198 @@
import { describe, expect, it } from "bun:test";
import { explainConditionBranches } from "./index.js";
import type { WorkflowTaskExecution } from "../../types.js";
describe("Workflow Condition Branch Diagnosis", () => {
const choose = (property = "value") => `@{choose('${JSON.stringify({ key: "source", properties: [{ key: property }] })}')}`;
const branch = (filter: any, status = "COMPLETED"): WorkflowTaskExecution => ({ id: "condition", name: "condition", type: "condition", status, tasks: [{ name: "child", type: "http" }], combineFilters: filter });
const diagnose = (actual: unknown, compare: string, expected: unknown) => explainConditionBranches([
{ id: "source", name: "source", type: "code", status: "COMPLETED", output: { value: actual } },
branch({ filters: [{ key: choose(), compare, value: expected }], condition: "AND" }),
])[0];
for (const [operator, actual, expected, matched] of [
["gt", 10, 5, true], ["gte", 5, 5, true], ["lt", 1, 5, true], ["lte", 5, 5, true],
["in", "A", ["A", "B"], true], ["not_in", "C", ["A", "B"], true],
["include", ["A"], "AB", false], ["not_include", ["A"], "AB", true],
["empty", false, null, false], ["empty", 0, null, false], ["empty", [], null, true],
["not_empty", 0, null, true], ["unsupported", 1, 1, null], ["gt", "text", 1, null],
["eq", null, null, true], ["eq", { amount: 10 }, 10, null],
] as const) {
it(`evaluates ${operator} without inventing a result (${JSON.stringify(actual)})`, () => {
expect(diagnose(actual, operator, expected)?.rules[0]?.matched).toBe(matched);
});
}
it("keeps all expected reference IDs rather than only the first", () => {
const tag = (key: string) => `@{value('${JSON.stringify({ key, label: key })}')}`;
expect(diagnose(["A", "B"], "eq", [tag("A"), tag("B")])?.rules[0]?.matched).toBe(true);
});
it("evaluates nested OR / AND groups and does not infer False from an incomplete execution tree", () => {
const result = explainConditionBranches([
{ id: "source", name: "source", type: "code", status: "COMPLETED", output: { value: 10 } },
branch({ condition: "OR", filters: [{ filters: [{ key: choose(), compare: "eq", value: 1 }] }, { filters: [{ key: choose(), compare: "gt", value: 5 }] }] }),
])[0];
expect(result?.evaluation).toBe(true);
expect(result?.hasSkippedTasks).toBe(false);
expect(result?.summary).toContain("执行树是否完整");
});
it("does not claim skipped tasks for a still-running condition or absent upstream evidence", () => {
const running = explainConditionBranches([branch({ filters: [{ key: choose(), compare: "eq", value: 1 }] }, "RUNNING")])[0];
expect(running?.evaluation).toBeNull();
expect(running?.rules[0]?.matched).toBeNull();
expect(running?.hasSkippedTasks).toBe(false);
expect(running?.summary).toContain("无法确定");
});
it("resolves nested branches against the matching loop instance", () => {
const tree = [1, 10].map((value, index) => ({ id: `loop-${index}`, name: "loop", type: "every", status: "COMPLETED", currentLoopPath: String(index), children: [
{ id: `source-${index}`, name: "source", type: "code", status: "COMPLETED", output: { value } },
{ ...branch({ filters: [{ key: choose(), compare: "gt", value: 5 }] }), id: `condition-${index}` },
] }));
const result = explainConditionBranches(tree);
expect(result.map(item => item.rules[0]?.actualValue)).toEqual([1, 10]);
expect(result.map(item => item.evaluation)).toEqual([false, true]);
});
it("recognizes an executed child by parentId even if the flat response order differs", () => {
const condition = branch({ filters: [] });
const result = explainConditionBranches([
{ id: "child", name: "child", parentId: condition.id, type: "http", status: "COMPLETED" },
condition,
]);
expect(result).toEqual([]);
});
it("diagnoses missing upstream property when property is absent from outputs", () => {
const tree: WorkflowTaskExecution[] = [
{
id: "exec-trigger",
name: "trigger_1",
label: "单据审批事件触发器",
type: "ekuaibao-flowform-trigger",
status: "COMPLETED",
output: { code: "ZJ-001" },
},
{
id: "exec-detail",
name: "action_detail",
label: "查询单据详情",
type: "flow-detail",
status: "COMPLETED",
output: {
approvers: ["ID_YANGJIE"],
},
},
{
id: "exec-condition",
name: "control_1",
label: "条件节点",
type: "condition",
status: "COMPLETED",
combineFilters: {
filters: [
{
filters: [
{
key: "@{choose('{\"key\":\"action_detail\",\"properties\":[{\"key\":\"currentApprovers\",\"label\":\"审批人\"}]}')}",
value: ["@{value('{\"key\":\"ID_YANGJIE\",\"label\":\"杨洁\"}')}"],
compare: "eq",
},
],
},
],
},
tasks: [
{
name: "action_http",
label: "自动审批",
type: "http",
},
],
} as any,
];
const res = explainConditionBranches(tree);
expect(res).toHaveLength(1);
expect(res[0].conditionNodeName).toBe("control_1");
expect(res[0].hasSkippedTasks).toBe(true);
expect(res[0].rules[0].isMissing).toBe(true);
expect(res[0].rules[0].upstreamProp).toBe("currentApprovers");
expect(res[0].summary).toContain("条件字段脱节");
});
it("diagnoses value mismatch when upstream property exists but values differ", () => {
const tree: WorkflowTaskExecution[] = [
{
id: "exec-trigger",
name: "trigger_1",
label: "单据审批事件触发器",
type: "ekuaibao-flowform-trigger",
status: "COMPLETED",
output: {
userInfo: "ID_ZANGKEXIN",
},
},
{
id: "exec-condition",
name: "control_1",
label: "条件节点",
type: "condition",
status: "COMPLETED",
combineFilters: {
filters: [
{
filters: [
{
key: "@{choose('{\"key\":\"trigger_1\",\"properties\":[{\"key\":\"userInfo\",\"label\":\"待处理人\"}]}')}",
value: "@{value('{\"key\":\"ID_YANGJIE\",\"label\":\"杨洁\"}')}",
compare: "eq",
},
],
},
],
},
tasks: [
{
name: "action_http",
label: "自动审批",
type: "http",
},
],
} as any,
];
const res = explainConditionBranches(tree);
expect(res).toHaveLength(1);
expect(res[0].hasSkippedTasks).toBe(true);
expect(res[0].rules[0].isMissing).toBe(false);
expect(res[0].rules[0].matched).toBe(false);
expect(res[0].rules[0].actualValue).toBe("ID_ZANGKEXIN");
});
it("returns empty diagnosis when child task was executed successfully", () => {
const tree: WorkflowTaskExecution[] = [
{
id: "exec-condition",
name: "control_1",
label: "条件节点",
type: "condition",
status: "COMPLETED",
tasks: [
{
name: "action_http",
label: "自动审批",
type: "http",
},
],
} as any,
{
id: "exec-http",
name: "action_http",
label: "自动审批",
type: "http",
status: "COMPLETED",
},
];
const res = explainConditionBranches(tree);
expect(res).toHaveLength(0);
});
});
@@ -0,0 +1,256 @@
import { describe, expect, it } from "bun:test";
import {
flattenWorkflowTaskTree,
findWorkflowTask,
reindexTasks,
addWorkflowTask,
editWorkflowTask,
removeWorkflowTask,
buildWorkflowTask,
summarizeTask,
} from "./index.js";
import type { WorkflowDetail, WorkflowTask } from "../../types.js";
const mockWorkflow: WorkflowDetail = {
id: "wf_test_100",
label: "发票风险处理流水线",
state: 0,
debugState: 0,
runTimes: 0,
errorTimes: 0,
updateTime: "2026-10-15",
version: "26.10.1",
dataLimit: 20,
source: 0,
queueJobs: false,
tasksVersion: 0,
tasks: [
{
name: "trigger_webhook_1",
type: "webhook",
label: "发票数据接入",
groupName: "trigger",
orderIndex: 0,
levelIndex: [0],
status: "active",
urlPath: "test-uuid-1",
params: [],
},
{
name: "control_every_1",
type: "every",
label: "循环发票明细",
desc: "依次遍历每张发票",
groupName: "control",
mode: "sequence",
batch: false,
list: "@{choose('body.invoices')}",
filters: [],
tasksMaxLevel: 1,
orderIndex: 1,
levelIndex: [1],
status: "active",
tasks: [
{
name: "action_js_1",
type: "code-js2",
label: "数据清洗",
groupName: "action",
orderIndex: 2,
levelIndex: [1, 0],
status: "active",
code: "return item.amount > 0;",
},
{
name: "control_cond_1",
type: "condition",
label: "超额判定",
groupName: "control",
combineFilters: { condition: "or", filters: [] },
tasksMaxLevel: 1,
orderIndex: 3,
levelIndex: [1, 1],
status: "active",
tasks: [
{
name: "action_stop_1",
type: "stop",
label: "阻断超额",
groupName: "control",
orderIndex: 4,
levelIndex: [1, 1, 0],
status: "active",
},
],
},
],
},
{
name: "action_http_1",
type: "http",
label: "通知外部系统",
groupName: "action",
method: "POST",
url: "https://api.example.com/notify",
orderIndex: 5,
levelIndex: [2],
status: "active",
},
],
};
describe("workflow-nodes - 任务节点声明式编排纯函数", () => {
it("flattenWorkflowTaskTree correctly flattens nested tree with depth and summary", () => {
const flattened = flattenWorkflowTaskTree(mockWorkflow.tasks);
expect(flattened).toHaveLength(6);
// 1. Webhook trigger
expect(flattened[0].hierarchicalIndex).toBe("1");
expect(flattened[0].task.name).toBe("trigger_webhook_1");
expect(flattened[0].depth).toBe(0);
expect(flattened[0].summary).toContain("urlPath: test-uuid-1");
// 2. Every container
expect(flattened[1].hierarchicalIndex).toBe("2");
expect(flattened[1].task.name).toBe("control_every_1");
expect(flattened[1].depth).toBe(0);
expect(flattened[1].summary).toContain("循环遍历");
// 3. Child in every container (code-js2)
expect(flattened[2].hierarchicalIndex).toBe("2.1");
expect(flattened[2].task.name).toBe("action_js_1");
expect(flattened[2].depth).toBe(1);
expect(flattened[2].parentName).toBe("control_every_1");
expect(flattened[2].summary).toContain("脚本 (23 字符)");
// 4. Condition in every container
expect(flattened[3].hierarchicalIndex).toBe("2.2");
expect(flattened[3].task.name).toBe("control_cond_1");
expect(flattened[3].depth).toBe(1);
// 5. Stop inside condition inside every
expect(flattened[4].hierarchicalIndex).toBe("2.2.1");
expect(flattened[4].task.name).toBe("action_stop_1");
expect(flattened[4].depth).toBe(2);
expect(flattened[4].summary).toBe("阻断终止流程");
// 6. Http top-level task
expect(flattened[5].hierarchicalIndex).toBe("3");
expect(flattened[5].task.name).toBe("action_http_1");
expect(flattened[5].depth).toBe(0);
expect(flattened[5].summary).toContain("POST https://api.example.com/notify");
});
it("findWorkflowTask finds nodes by name, hierarchical index, or global number", () => {
// By name
const byName = findWorkflowTask(mockWorkflow.tasks, "action_js_1");
expect(byName).not.toBeNull();
expect(byName?.task.label).toBe("数据清洗");
expect(byName?.hierarchicalIndex).toBe("2.1");
expect(byName?.path).toBe("tasks.1.tasks.0");
// By hierarchical index
const byHierarchical = findWorkflowTask(mockWorkflow.tasks, "2.2.1");
expect(byHierarchical).not.toBeNull();
expect(byHierarchical?.task.name).toBe("action_stop_1");
// By global sequential index number
const byGlobalIndex = findWorkflowTask(mockWorkflow.tasks, 3);
expect(byGlobalIndex).not.toBeNull();
expect(byGlobalIndex?.task.name).toBe("action_js_1");
// Non-existent target
const notFound = findWorkflowTask(mockWorkflow.tasks, "non_existent_node");
expect(notFound).toBeNull();
});
it("reindexTasks recalculates orderIndex and levelIndex consistently", () => {
const clonedTasks: WorkflowTask[] = JSON.parse(JSON.stringify(mockWorkflow.tasks));
// Mess up indices
clonedTasks[0].orderIndex = 99;
clonedTasks[1].levelIndex = [9, 9];
reindexTasks(clonedTasks);
expect(clonedTasks[0].orderIndex).toBe(0);
expect(clonedTasks[0].levelIndex).toEqual([0]);
expect(clonedTasks[1].orderIndex).toBe(1);
expect(clonedTasks[1].levelIndex).toEqual([1]);
expect(clonedTasks[1].tasks![0].orderIndex).toBe(2);
expect(clonedTasks[1].tasks![0].levelIndex).toEqual([1, 0]);
expect(clonedTasks[1].tasks![1].tasks![0].orderIndex).toBe(4);
expect(clonedTasks[1].tasks![1].tasks![0].levelIndex).toEqual([1, 1, 0]);
});
it("addWorkflowTask appends to root, inserts after node, and inserts into parent container", () => {
// 1. Append to root
const { workflow: wfAppended, newTask: appendedTask } = addWorkflowTask(mockWorkflow, {
type: "code-js2",
label: "末尾数据汇总",
code: "return { total: 100 };",
});
expect(wfAppended.tasks).toHaveLength(4);
expect(appendedTask.label).toBe("末尾数据汇总");
expect(wfAppended.tasks[3].name).toBe(appendedTask.name);
expect(wfAppended.tasks[3].levelIndex).toEqual([3]);
// 2. Insert into parent container
const { workflow: wfParent, newTask: parentTask } = addWorkflowTask(mockWorkflow, {
type: "stop",
label: "循环中终止",
parent: "control_every_1",
});
const everyNode = wfParent.tasks[1];
expect(everyNode.tasks).toHaveLength(3);
expect(everyNode.tasks![2].name).toBe(parentTask.name);
expect(everyNode.tasks![2].levelIndex).toEqual([1, 2]);
// 3. Insert after specific node
const { workflow: wfAfter, newTask: afterTask } = addWorkflowTask(mockWorkflow, {
type: "code",
label: "MVEL计算节点",
after: "action_js_1",
code: "return 1 + 1;",
});
const everyTasks = wfAfter.tasks[1].tasks!;
expect(everyTasks).toHaveLength(3);
expect(everyTasks[0].name).toBe("action_js_1");
expect(everyTasks[1].name).toBe(afterTask.name); // Inserted right after
expect(everyTasks[1].label).toBe("MVEL计算节点");
expect(everyTasks[1].levelIndex).toEqual([1, 1]);
});
it("editWorkflowTask updates label, code, and custom properties", () => {
const { workflow: wfEdited, editedTask } = editWorkflowTask(mockWorkflow, "action_js_1", {
label: "数据清洗升级版",
code: "return item.amount > 500;",
desc: "只保留大于500的发票",
set: { customTag: "finance-audit" },
});
expect(editedTask.label).toBe("数据清洗升级版");
expect((editedTask as any).code).toBe("return item.amount > 500;");
expect(editedTask.desc).toBe("只保留大于500的发票");
expect((editedTask as any).customTag).toBe("finance-audit");
// Original workflow must not be mutated
expect(mockWorkflow.tasks[1].tasks![0].label).toBe("数据清洗");
});
it("removeWorkflowTask safely removes task and guards trigger node", () => {
// 1. Remove child task in container
const { workflow: wfRemoved, removedTask } = removeWorkflowTask(mockWorkflow, "action_js_1");
expect(removedTask.name).toBe("action_js_1");
expect(wfRemoved.tasks[1].tasks).toHaveLength(1);
expect(wfRemoved.tasks[1].tasks![0].name).toBe("control_cond_1");
expect(wfRemoved.tasks[1].tasks![0].levelIndex).toEqual([1, 0]); // Re-indexed to 0
// 2. Trigger protection: removing primary trigger when other tasks exist throws ValidationError
expect(() => {
removeWorkflowTask(mockWorkflow, "trigger_webhook_1");
}).toThrow("触发源节点");
});
});
@@ -0,0 +1,226 @@
import { describe, expect, it } from "bun:test";
import {
hasReturnStatement,
lintJavaScriptCode,
lintMvelCode,
lintWorkflowScripts,
executeJavaScriptSandbox,
} from "./index.js";
import type { WorkflowDetail } from "../../types.js";
describe("workflow-script - 本地静态语法校验与沙箱仿真引擎", () => {
describe("hasReturnStatement", () => {
it("identifies return statement correctly", () => {
expect(hasReturnStatement("const x = 1;\nreturn x + 2;")).toBe(true);
expect(hasReturnStatement("// return 123;\nconst x = 1;")).toBe(false);
expect(hasReturnStatement("/*\n * return false;\n */\nconst y = 2;")).toBe(false);
expect(hasReturnStatement("const x = 'returning';")).toBe(false);
});
});
describe("lintJavaScriptCode", () => {
it("reports error for empty script", () => {
const res = lintJavaScriptCode(" ");
expect(res.issues.some((i) => i.rule === "empty-script")).toBe(true);
expect(res.hasReturn).toBe(false);
});
it("warns about missing return statement", () => {
const res = lintJavaScriptCode("const a = 1; const b = 2;");
expect(res.issues.some((i) => i.rule === "missing-return")).toBe(true);
expect(res.hasReturn).toBe(false);
});
it("catches syntax errors with line numbers", () => {
const res = lintJavaScriptCode("const a = 1;\nconst b = ;\nreturn a + b;");
expect(res.issues.some((i) => i.rule === "syntax-error" && i.level === "error")).toBe(true);
});
it("accepts valid JavaScript with declared bound variables", () => {
const code = `
const filtered = items.filter(x => x.amount > 0);
return { count: filtered.length, items: filtered };
`;
const res = lintJavaScriptCode(code, ["items"]);
expect(res.issues).toHaveLength(0);
expect(res.hasReturn).toBe(true);
});
});
describe("lintMvelCode", () => {
it("detects unclosed brackets in MVEL code", () => {
const code = "var a = HashMap();\na.put('key', 123;";
const res = lintMvelCode(code);
expect(res.issues.some((i) => i.rule === "unclosed-bracket")).toBe(true);
});
it("detects mismatched brackets", () => {
const code = "var a = (1 + 2]; return a;";
const res = lintMvelCode(code);
expect(res.issues.some((i) => i.rule === "unmatched-brackets")).toBe(true);
});
it("flags dangling node references if node does not exist in workflow", () => {
const code = `
var upstream = action_non_existent;
var r = new HashMap();
r.put("data", upstream);
return r;
`;
const existing = new Set(["trigger_webhook", "action_calc"]);
const res = lintMvelCode(code, existing);
expect(res.issues.some((i) => i.rule === "dangling-node-reference")).toBe(true);
expect(res.referencedNodes).toHaveLength(1);
expect(res.referencedNodes[0].name).toBe("action_non_existent");
expect(res.referencedNodes[0].exists).toBe(false);
});
it("passes clean MVEL code referencing existing nodes", () => {
const code = `
import java.util.HashMap;
var upstream = action_calc;
var result = new HashMap();
result.put("val", upstream);
return result;
`;
const existing = new Set(["trigger_webhook", "action_calc"]);
const res = lintMvelCode(code, existing);
expect(res.issues).toHaveLength(0);
expect(res.referencedNodes[0].exists).toBe(true);
});
});
describe("lintWorkflowScripts", () => {
it("scans and reports issues across all workflow code nodes", () => {
const mockWorkflow = {
id: "pipe_lint_test",
label: "测试流程",
state: 0,
tasks: [
{
name: "trigger_1",
type: "webhook",
label: "触发器",
groupName: "trigger",
orderIndex: 0,
levelIndex: [0],
status: "active",
},
{
name: "action_js_bad",
type: "code-js2",
label: "语法错误JS",
groupName: "action",
orderIndex: 1,
levelIndex: [1],
status: "active",
code: "const x = ; return x;",
mapping: [],
},
{
name: "action_mvel_good",
type: "code",
label: "正常MVEL",
groupName: "action",
orderIndex: 2,
levelIndex: [2],
status: "active",
code: "var a = trigger_1; return a;",
},
],
} as unknown as WorkflowDetail;
const report = lintWorkflowScripts(mockWorkflow);
expect(report.totalCodeNodes).toBe(2);
expect(report.validCount).toBe(1);
expect(report.invalidCount).toBe(1);
expect(report.allValid).toBe(false);
const badReport = report.reports.find((r) => r.nodeName === "action_js_bad");
expect(badReport?.valid).toBe(false);
expect(badReport?.issues.some((i) => i.rule === "syntax-error")).toBe(true);
const goodReport = report.reports.find((r) => r.nodeName === "action_mvel_good");
expect(goodReport?.valid).toBe(true);
});
});
describe("executeJavaScriptSandbox", () => {
it("executes code in sandbox and returns computed values", async () => {
const code = `
console.log("Processing records:", items.length);
const total = items.reduce((sum, item) => sum + item.amount, 0);
return { total, count: items.length };
`;
const inputs = {
items: [{ amount: 100 }, { amount: 250 }, { amount: 50 }],
};
const res = await executeJavaScriptSandbox(code, inputs);
expect(res.success).toBe(true);
expect(res.returnValue).toEqual({ total: 400, count: 3 });
expect(res.logs).toHaveLength(1);
expect(res.logs[0].message).toContain("Processing records: 3");
expect(res.durationMs).toBeGreaterThanOrEqual(0);
});
it("catches runtime errors and reports line number", async () => {
const code = `
const a = 10;
const b = undefined;
return b.nonExistentField.subField;
`;
const res = await executeJavaScriptSandbox(code, {});
expect(res.success).toBe(false);
expect(res.error).toBeDefined();
expect(res.error?.name).toBe("TypeError");
expect(res.error?.message).toContain("undefined");
expect(res.error?.line).toBe(4);
});
it("terminates on infinite loops via timeout", async () => {
const code = "while (true) {}";
const res = await executeJavaScriptSandbox(code, {}, { timeoutMs: 100 });
expect(res.success).toBe(false);
expect(res.error?.message).toContain("timed out");
});
});
});
describe("MVEL lexical boundaries", () => {
for (const code of [
'return "{";',
'return wrap("https://example.test/path");',
'/* { action_missing */\nreturn 1;',
'return "action_missing";',
"return 'escaped \\' { action_missing';",
'/* comment with "quotes" and // */\r\nreturn [1, 2]; // { action_missing',
]) {
it(`ignores literals and comments in ${JSON.stringify(code)}`, () => {
const result = lintMvelCode(code, new Set());
expect(result.issues).toEqual([]);
expect(result.referencedNodes).toEqual([]);
expect(result.hasReturn).toBe(true);
});
}
it("does not count quoted or commented return as executable code", () => {
const result = lintMvelCode('value = "return"; /* return 1; */ // return 2;');
expect(result.hasReturn).toBe(false);
expect(result.issues.map(i => i.rule)).toEqual(["missing-return"]);
});
it("keeps real references and error coordinates while diagnosing unfinished literals", () => {
const result = lintMvelCode('// ]\nreturn action_missing;]', new Set());
expect(result.issues.find(i => i.rule === "unmatched-brackets")).toMatchObject({ line: 2, column: 23 });
expect(result.issues.find(i => i.rule === "dangling-node-reference")?.level).toBe("error");
expect(lintMvelCode('return "unfinished').issues.some(i => i.rule === "unterminated-string")).toBe(true);
expect(lintMvelCode('return 1;\n /* unfinished').issues.find(i => i.rule === "unterminated-comment")).toMatchObject({ line: 2, column: 3 });
});
it("does not invalidate an entire workflow for literal-only node names", () => {
const result = lintWorkflowScripts({ id: "lexical", tasks: [{ name: "action_code", type: "code", code: 'return "action_missing {";' }] } as unknown as WorkflowDetail);
expect(result.allValid).toBe(true);
});
});
@@ -1,6 +1,62 @@
import type { WorkflowTask } from "../../types.js";
import type { ScriptIssue } from "./types.js";
import { hasReturnStatement } from "./lint-js.js";
/** Mask literals/comments without moving offsets used by diagnostics. */
function scanMvelCode(code: string, issues: ScriptIssue[]): string {
const masked = code.split("");
let mode: "code" | "line" | "block" | "'" | '"' = "code";
let start = { line: 1, column: 1 };
let line = 1;
let column = 1;
let escaped = false;
for (let i = 0; i < code.length; i++) {
const ch = code[i];
const next = code[i + 1];
if (mode === "code") {
if (ch === "'" || ch === '"') {
mode = ch;
start = { line, column };
masked[i] = " ";
} else if (ch === "/" && (next === "/" || next === "*")) {
mode = next === "/" ? "line" : "block";
start = { line, column };
masked[i] = masked[i + 1] = " ";
i++;
column++;
}
} else {
if (ch !== "\n" && ch !== "\r") masked[i] = " ";
if (mode === "line") {
if (ch === "\n" || ch === "\r") mode = "code";
} else if (mode === "block") {
if (ch === "*" && next === "/") {
masked[++i] = " ";
column++;
mode = "code";
}
} else if (escaped) {
escaped = false;
} else if (ch === "\\") {
escaped = true;
} else if (ch === mode) {
mode = "code";
}
}
if (ch === "\n") { line++; column = 1; }
else column++;
}
if (mode === "block" || mode === "'" || mode === '"') {
issues.push({
level: "error",
...start,
rule: mode === "block" ? "unterminated-comment" : "unterminated-string",
message: mode === "block" ? "未闭合的块注释" : `未闭合的字符串: ${mode}`,
});
}
return masked.join("");
}
/**
* 静态检查 MVEL (code) 括号闭合与上游节点引用有效性
@@ -26,7 +82,8 @@ export function lintMvelCode(
return { issues, referencedNodes, hasReturn: false };
}
const hasRet = hasReturnStatement(code);
const executableCode = scanMvelCode(code, issues);
const hasRet = /\breturn\b/.test(executableCode);
if (!hasRet) {
issues.push({
level: "warning",
@@ -37,12 +94,12 @@ export function lintMvelCode(
// 1. 括号与引号对称性平衡检查
const stack: Array<{ char: string; line: number }> = [];
const lines = code.split(/\r?\n/);
const lines = executableCode.split(/\r?\n/);
for (let l = 0; l < lines.length; l++) {
const lineText = lines[l];
// 忽略单行注释
const cleanLine = lineText.replace(/\/\/.*$/, "");
// 忽略单行注释,以及扫描器已屏蔽的字符串与块注释。
const cleanLine = lineText;
for (let c = 0; c < cleanLine.length; c++) {
const ch = cleanLine[c];
@@ -80,7 +137,7 @@ export function lintMvelCode(
const foundRefs = new Set<string>();
let match: RegExpExecArray | null;
while ((match = nodeRefRegex.exec(code)) !== null) {
while ((match = nodeRefRegex.exec(executableCode)) !== null) {
foundRefs.add(match[1]);
}
@@ -0,0 +1,399 @@
import { describe, expect, it } from "bun:test";
import {
beginWorkflowSave,
applyWorkflowPathPatch,
commitWorkflowSave,
createWorkflowDraft,
failWorkflowSave,
hasWorkflowVersionConflict,
patchWorkflowDraft,
} from "./index.js";
import { WorkflowDetailSchema } from "../../types.js";
import type { WorkflowDetail } from "../../types.js";
import {
getExecutionLogs,
getJob,
getJobExecutionLevel,
getJobExecutionTree,
getJobFailedExecutions,
getWorkflowDetail,
listWorkflowSnapshots,
listWorkflowLogs,
toggleWorkflow,
updateWorkflow,
} from "../../api.js";
import {
extractFailureExecutions,
findExecutionNode,
flattenExecutionTree,
isTaskExecutionFailed,
} from "../../services.js";
import { AuthenticationError, EkbApiError } from "../../../../core/errors.js";
import { WorkflowAlertStore } from "../alert/index.js";
import { mkdtempSync, readFileSync, rmSync } from "node:fs";
import { join } from "node:path";
const workflow = (overrides: Partial<WorkflowDetail> = {}): WorkflowDetail => WorkflowDetailSchema.parse({
id: "wf-1",
label: "测试流程",
state: 0,
debugState: 0,
runTimes: 0,
errorTimes: 0,
updateTime: "",
version: "1",
dataLimit: 20,
source: 1,
queueJobs: false,
tasksVersion: 3,
tasks: [],
...overrides,
});
describe("workflow draft state machine", () => {
it("patches a nested node field without mutating the source snapshot", () => {
const source = workflow({ tasks: [{ name: "task-1", type: "code", label: "旧值", groupName: "", orderIndex: 0, levelIndex: [0], status: "ok", code: "return 1;" }] });
const patched = applyWorkflowPathPatch(source, "tasks[0].code", "return 2;");
expect(patched.tasks[0]?.code).toBe("return 2;");
expect(source.tasks[0]?.code).toBe("return 1;");
});
it("rejects a path whose parent does not exist", () => {
expect(() => applyWorkflowPathPatch(workflow(), "tasks.0.form.title", "x")).toThrow("路径不存在");
});
it("sends the complete workflow snapshot to the Piper update endpoint", async () => {
let request: { url: string; json: WorkflowDetail } | undefined;
const client = {
put: async (url: string, options: { json: WorkflowDetail }) => {
request = { url, json: options.json };
return { json: async () => ({ data: options.json }) };
},
} as any;
const input = workflow({ inputs: [{ key: "$platformId", value: "platform-1" }], "$snapshot": [{ key: "tasks.0", value: "{}" }] });
const result = await updateWorkflow(client, input);
expect(request?.url).toBe("api/easo/pipelines/wf-1");
expect(request?.json.inputs).toEqual([{ key: "$platformId", value: "platform-1" }]);
expect(result["$snapshot"]).toEqual([{ key: "tasks.0", value: "{}" }]);
});
it("reads snapshot history and accepts the web API's serialized inputs", async () => {
let request: { url: string; options: any } | undefined;
const client = {
get: async (url: string, options: any) => {
request = { url, options };
return new Response(JSON.stringify({ data: {
number: 1,
size: 10,
totalPages: 1,
totalItems: 1,
items: [{
id: "snapshot-1",
pipelineId: "wf-1",
platformId: "platform-1",
inputs: '[{"key":"$platformId","value":"platform-1"}]',
outputs: "[]",
version: "26.2.38",
}],
} }));
},
} as any;
const result = await listWorkflowSnapshots(client, "wf-1", 2, 5);
expect(request?.url).toBe("api/easo/pipelines/wf-1/snapshots");
expect(request?.options.searchParams).toEqual({ number: "2", pageSize: "5" });
expect(result.items[0]?.inputs).toContain("$platformId");
expect(result.items[0]?.version).toBe("26.2.38");
});
it("reads workflow logs with the web query contract", async () => {
let request: { url: string; options: any } | undefined;
const client = {
get: async (url: string, options: any) => {
request = { url, options };
return new Response(JSON.stringify({ data: { number: 1, size: 10, totalItems: 1, items: [{ id: "run-1", state: "FAILED", message: "测试错误" }] } }));
},
} as any;
const result = await listWorkflowLogs(client, "wf-1", { state: "FAILED", startTime: "2026-09-01", endTime: "2026-09-09" });
expect(request?.url).toBe("api/easo/pipelines/wf-1/log");
expect(request?.options.searchParams).toEqual({ state: "FAILED", number: "1", pageSize: "10", startTime: "2026-09-01", endTime: "2026-09-09" });
expect(result.items[0]?.message).toBe("测试错误");
});
it("uses the state endpoint for publishing a workflow", async () => {
let request: { url: string; options: any } | undefined;
const client = {
put: async (url: string, options: any) => {
request = { url, options };
return new Response(JSON.stringify({ code: 200, msg: "更新成功", data: null }), { status: 200 });
},
} as any;
const result = await toggleWorkflow(client, "wf-1", 1);
expect(result.success).toBe(true);
expect(request?.url).toBe("api/easo/pipelines/state/wf-1");
expect(request?.options.searchParams).toEqual({ state: "1" });
});
it("persists workflow alert fingerprints and only reports new counts", () => {
const dir = mkdtempSync("hose-workflow-alert-");
const file = join(dir, "alerts.json");
const store = new WorkflowAlertStore(file);
const alert = { id: "corp:platform:wf-1", pipelineId: "wf-1", platformId: "platform-1", pipelineName: "测试流程", errorCount: 1, state: 0, observedAt: 1 };
expect(store.observe([alert]).newAlerts).toHaveLength(1);
expect(store.observe([{ ...alert, observedAt: 2 }]).newAlerts).toHaveLength(0);
expect(store.observe([{ ...alert, errorCount: 2, observedAt: 3 }]).newAlerts).toHaveLength(1);
expect(store.observe([]).newAlerts).toHaveLength(0);
expect(store.observe([{ ...alert, observedAt: 4 }]).newAlerts).toHaveLength(1);
expect(JSON.parse(readFileSync(file, "utf8")).version).toBe(1);
rmSync(dir, { recursive: true, force: true });
});
it("tracks dirty revisions and commits the server snapshot", () => {
let state = createWorkflowDraft(workflow());
state = patchWorkflowDraft(state, (current) => ({ ...current, label: "已修改" }), ["label"]);
expect(state.status).toBe("dirty");
expect(state.revision).toBe(1);
expect(state.dirtyPaths).toEqual(["label"]);
state = beginWorkflowSave(state);
expect(state.status).toBe("saving");
state = commitWorkflowSave(state, workflow({ label: "已修改", tasksVersion: 4 }));
expect(state.status).toBe("saved");
expect(state.dirtyPaths).toEqual([]);
expect(state.baseTasksVersion).toBe(4);
});
it("detects optimistic concurrency conflicts and preserves failures", () => {
const state = createWorkflowDraft(workflow());
expect(hasWorkflowVersionConflict(state, workflow({ tasksVersion: 4 }))).toBe(true);
const failed = failWorkflowSave(beginWorkflowSave(patchWorkflowDraft(state, (current) => current)), "网络错误");
expect(failed.status).toBe("failed");
expect(failed.error).toBe("网络错误");
});
it("throws structured AuthenticationError or EkbApiError when Piper unwrap receives null data or non-200 code", async () => {
const unauthorizedClient = {
get: async () =>
new Response(JSON.stringify({ code: 401, message: "登录已过期", data: null }), {
status: 200,
}),
} as any;
await expect(getWorkflowDetail(unauthorizedClient, "wf-1")).rejects.toBeInstanceOf(AuthenticationError);
const nullDataClient = {
get: async () =>
new Response(JSON.stringify({ code: 200, msg: "pipeline not found", data: null }), {
status: 200,
}),
} as any;
await expect(getWorkflowDetail(nullDataClient, "wf-1")).rejects.toBeInstanceOf(EkbApiError);
});
it("calls the 5 Piper Job diagnostic endpoints and parses execution trees, failed nodes, child levels, and logs", async () => {
const client = {
get: async (url: string, options?: any) => {
if (url === "api/easo/jobs/892809886382563347") {
return new Response(
JSON.stringify({
code: 200,
data: {
id: "892809886382563347",
pipelineId: "886351399301758976",
label: "每30分钟创建采购申请单",
state: "COMPLETED",
successTaskCount: 5,
errorTaskCount: 1,
hasError: true,
},
})
);
}
if (url === "api/easo/jobs/892809886382563347/execution") {
return new Response(
JSON.stringify({
code: 200,
data: [
{
id: "892809893789696012",
jobId: "892809886382563347",
name: "every_0",
label: "循环",
type: "every",
state: "COMPLETED",
levelIndex: [0],
},
],
})
);
}
if (url === "api/easo/jobs/892809886382563347/execution/level/failed") {
return new Response(
JSON.stringify({
code: 200,
data: [
{
id: "892809900000000001",
jobId: "892809886382563347",
parentId: "892809893789696012",
name: "ekuaibao_flow_create_task_0",
label: "创建预付申请单",
type: "flow-create-task",
state: "FAILED",
inputs: { form: { u_关联合同流程: "ID01VSau4VJWSH" } },
outputs: { error: "我方签约主体未填写" },
},
],
})
);
}
if (url === "api/easo/jobs/892809886382563347/execution/level") {
expect(options?.searchParams).toEqual({
parentId: "892809893789696012",
number: "1",
pageSize: "20",
});
return new Response(
JSON.stringify({
code: 200,
data: {
number: 1,
size: 20,
totalPages: 1,
totalItems: 1,
items: [
[
{
id: "892809900000000001",
name: "ekuaibao_flow_create_task_0",
state: "FAILED",
inputs: { form: { u_关联合同流程: "ID01VSau4VJWSH" } },
outputs: { error: "我方签约主体未填写" },
},
],
],
},
})
);
}
if (url === "api/easo/executions/892809893789696012/logs") {
return new Response(
JSON.stringify({
code: 200,
data: {
total: 1,
items: [{ id: "log-1", message: "MVEL script executed", level: "INFO" }],
},
})
);
}
throw new Error(`Unexpected URL: ${url}`);
},
} as any;
const job = await getJob(client, "892809886382563347");
expect(job.hasError).toBe(true);
expect(job.errorTaskCount).toBe(1);
const tree = await getJobExecutionTree(client, "892809886382563347");
expect(tree).toHaveLength(1);
expect(tree[0]?.name).toBe("every_0");
const failed = await getJobFailedExecutions(client, "892809886382563347");
expect(failed.items).toHaveLength(1);
expect((failed.items[0]?.outputs as any)?.error).toBe("我方签约主体未填写");
const level = await getJobExecutionLevel(client, "892809886382563347", {
parentId: "892809893789696012",
});
expect(level.items).toHaveLength(1);
const logs = await getExecutionLogs(client, "892809893789696012");
expect(logs[0]?.message).toBe("MVEL script executed");
});
describe("execution tree inspection & failure extraction helpers", () => {
const mockTree: any[] = [
{
id: "node_1",
name: "start_node",
type: "start",
status: "COMPLETED",
children: [
{
id: "node_2",
name: "loop_node",
type: "loop",
status: "COMPLETED",
tasks: [
{
id: "node_3",
name: "approve_node",
displayName: "资金调拨自动审批",
type: "flow-approval",
status: "FAILED",
error: { message: "400: 无待办审批事项" },
inputs: { formId: "ZJ-001368", action: "agree" },
},
],
},
],
},
{
id: "node_4",
name: "notice_node",
displayName: "钉钉通知",
type: "dingtalk",
status: "COMPLETED",
},
];
it("flattenExecutionTree flattens nested children and tasks recursively", () => {
const flattened = flattenExecutionTree(mockTree);
expect(flattened).toHaveLength(4);
expect(flattened.map((n) => n.id)).toEqual(["node_1", "node_2", "node_3", "node_4"]);
});
it("isTaskExecutionFailed identifies various failure indicators", () => {
expect(isTaskExecutionFailed({ id: "1", type: "x", status: "FAILED" })).toBe(true);
expect(
isTaskExecutionFailed({
id: "2",
type: "x",
status: "RUNNING",
error: { message: "timeout", stackTrace: [] },
})
).toBe(true);
expect(isTaskExecutionFailed({ id: "3", type: "x", status: "OK", outputs: { error: "reject" } } as any)).toBe(true);
expect(isTaskExecutionFailed({ id: "4", type: "x", status: "COMPLETED" })).toBe(false);
});
it("extractFailureExecutions merges failures from tree and failed items without duplicates", () => {
const failedPageItems: any[] = [
{
id: "node_3",
name: "approve_node",
status: "FAILED",
outputs: { details: "failed downstream" },
},
];
const failures = extractFailureExecutions(mockTree, failedPageItems);
expect(failures).toHaveLength(1);
expect(failures[0].id).toBe("node_3");
expect(failures[0].error?.message).toBe("400: 无待办审批事项");
expect((failures[0] as any).inputs?.formId).toBe("ZJ-001368");
expect((failures[0] as any).outputs?.details).toBe("failed downstream");
});
it("findExecutionNode matches by id, exact name, or partial display name", () => {
const byId = findExecutionNode(mockTree, "node_3");
expect(byId?.id).toBe("node_3");
const byName = findExecutionNode(mockTree, "approve_node");
expect(byName?.id).toBe("node_3");
const byDisplayName = findExecutionNode(mockTree, "资金调拨");
expect(byDisplayName?.id).toBe("node_3");
const notFound = findExecutionNode(mockTree, "non_existent");
expect(notFound).toBeUndefined();
});
});
});
@@ -0,0 +1,374 @@
import { describe, expect, it } from "bun:test";
import {
TaskExecutionTracker,
formatWatchEvent,
normalizeJobStatus,
isJobTerminal,
extractTaskErrorMessage,
watchSingleJob,
watchWorkflowPipeline,
type WorkflowWatchEvent,
} from "./index.js";
import type { WorkflowTaskExecution } from "../../types.js";
describe("workflow-watch - 实时监控与日志流跟踪引擎", () => {
describe("TaskExecutionTracker", () => {
it("tracks new nodes and produces correct initial events", () => {
const tracker = new TaskExecutionTracker("job_123");
const mockNodes: WorkflowTaskExecution[] = [
{
id: "exec_1",
name: "trigger_clock",
type: "clock",
label: "定时触发",
status: "COMPLETED",
executionTime: 12,
},
{
id: "exec_2",
name: "action_js",
type: "code-js2",
label: "数据清洗",
status: "RUNNING",
},
{
id: "exec_3",
name: "action_http",
type: "http",
status: "FAILED",
executionTime: 450,
error: { message: "HTTP 502 Bad Gateway", stackTrace: [] },
},
{
id: "exec_4",
name: "action_create",
type: "flow-create-task",
status: "SKIPPED",
executionTime: 120,
currentLoopPath: "every_1:0",
output: { error: "送审失败: 缺失经办人" },
},
];
const events = tracker.processExecutions(mockNodes);
expect(events).toHaveLength(4);
expect(events[0].type).toBe("task_completed");
expect(events[0].name).toBe("trigger_clock");
expect(events[0].durationMs).toBe(12);
expect(events[1].type).toBe("task_started");
expect(events[1].name).toBe("action_js");
expect(events[1].status).toBe("RUNNING");
expect(events[2].type).toBe("task_failed");
expect(events[2].name).toBe("action_http");
expect(events[2].error).toBe("HTTP 502 Bad Gateway");
expect(events[3].type).toBe("task_skipped");
expect(events[3].name).toBe("action_create");
expect(events[3].error).toBe("送审失败: 缺失经办人");
expect(events[3].loopPath).toBe("every_1:0");
});
it("does not re-emit events if node status has not changed on subsequent poll", () => {
const tracker = new TaskExecutionTracker("job_123");
const mockNodes: WorkflowTaskExecution[] = [
{
id: "exec_1",
name: "trigger_clock",
type: "clock",
status: "COMPLETED",
},
{
id: "exec_2",
name: "action_js",
type: "code-js2",
status: "RUNNING",
},
];
const initialEvents = tracker.processExecutions(mockNodes);
expect(initialEvents).toHaveLength(2);
// 相同状态再次轮询
const repeatEvents = tracker.processExecutions(mockNodes);
expect(repeatEvents).toHaveLength(0);
});
it("detects status transitions from RUNNING to COMPLETED", () => {
const tracker = new TaskExecutionTracker("job_123");
const initialNodes: WorkflowTaskExecution[] = [
{
id: "exec_2",
name: "action_js",
type: "code-js2",
status: "RUNNING",
},
];
tracker.processExecutions(initialNodes);
// 节点完成
const updatedNodes: WorkflowTaskExecution[] = [
{
id: "exec_2",
name: "action_js",
type: "code-js2",
status: "COMPLETED",
executionTime: 230,
},
];
const transitionedEvents = tracker.processExecutions(updatedNodes);
expect(transitionedEvents).toHaveLength(1);
expect(transitionedEvents[0].type).toBe("task_completed");
expect(transitionedEvents[0].status).toBe("COMPLETED");
expect(transitionedEvents[0].durationMs).toBe(230);
});
});
describe("extractTaskErrorMessage", () => {
it("extracts error from error.message", () => {
const node: WorkflowTaskExecution = {
id: "e1",
status: "FAILED",
type: "code",
error: { message: "Syntax error at line 3", stackTrace: [] },
};
expect(extractTaskErrorMessage(node)).toBe("Syntax error at line 3");
});
it("extracts error from outputs.error", () => {
const node: any = {
id: "e2",
status: "SKIPPED",
type: "http",
outputs: { error: "Connection timed out" },
};
expect(extractTaskErrorMessage(node)).toBe("Connection timed out");
});
});
describe("normalizeJobStatus and isJobTerminal", () => {
it("normalizes various string and numeric states", () => {
expect(normalizeJobStatus({ status: "running" })).toBe("RUNNING");
expect(normalizeJobStatus({ state: 0 })).toBe("COMPLETED");
expect(normalizeJobStatus({ state: 1 })).toBe("RUNNING");
expect(normalizeJobStatus({ state: 2 })).toBe("FAILED");
expect(normalizeJobStatus(null)).toBe("UNKNOWN");
});
it("checks terminal states", () => {
expect(isJobTerminal("COMPLETED")).toBe(true);
expect(isJobTerminal("FAILED")).toBe(true);
expect(isJobTerminal("STOP")).toBe(true);
expect(isJobTerminal("RUNNING")).toBe(false);
expect(isJobTerminal("UNKNOWN")).toBe(false);
});
});
describe("formatWatchEvent", () => {
it("formats various watch events cleanly", () => {
const now = new Date("2026-10-15T16:00:00.000Z").getTime();
const startEv: WorkflowWatchEvent = {
type: "pipeline_watch_start",
pipelineId: "pipe_100",
pipelineLabel: "发票自动归档",
timestamp: now,
};
expect(formatWatchEvent(startEv)).toContain("开始监听工作流 [发票自动归档]");
const jobEv: WorkflowWatchEvent = {
type: "job_detected",
jobId: "job_999",
status: "RUNNING",
runType: "DEBUG",
timestamp: now,
};
expect(formatWatchEvent(jobEv)).toContain("捕获新运行任务 Job [job_999]");
const completedEv: WorkflowWatchEvent = {
type: "task_completed",
jobId: "job_999",
name: "action_js",
label: "清洗数据",
taskType: "code-js2",
durationMs: 88,
timestamp: now,
};
expect(formatWatchEvent(completedEv)).toContain("✓ [code-js2] action_js (清洗数据) COMPLETED (88ms)");
const failedEv: WorkflowWatchEvent = {
type: "task_failed",
jobId: "job_999",
name: "action_http",
taskType: "http",
durationMs: 500,
error: "网络连接失败",
timestamp: now,
};
const formattedFailed = formatWatchEvent(failedEv);
expect(formattedFailed).toContain("❌ [http] action_http FAILED");
expect(formattedFailed).toContain("网络连接失败");
const skippedEv: WorkflowWatchEvent = {
type: "task_skipped",
jobId: "job_999",
name: "action_create",
taskType: "flow-create-task",
durationMs: 120,
loopPath: "every_1:0",
error: "金额超标跳过",
timestamp: now,
};
const formattedSkipped = formatWatchEvent(skippedEv);
expect(formattedSkipped).toContain("⚠️ [flow-create-task] action_create SKIPPED");
expect(formattedSkipped).toContain("金额超标跳过");
const endEv: WorkflowWatchEvent = {
type: "job_completed",
jobId: "job_999",
timestamp: now,
jobSummary: {
status: "COMPLETED",
durationMs: 1500,
successCount: 5,
errorCount: 1,
hasError: true,
},
};
expect(formatWatchEvent(endEv)).toContain("Job [job_999] 执行结束: 状态 [COMPLETED]");
expect(formatWatchEvent(endEv)).toContain("存在错误: 是");
});
});
describe("watchSingleJob and watchWorkflowPipeline with Mock Client", () => {
it("watchSingleJob tracks a job through completion", async () => {
const mockJob = {
id: "job_test_1",
pipelineId: "pipe_1",
status: "COMPLETED",
runType: "DEBUG",
durationTime: 1200,
successTaskCount: 2,
errorTaskCount: 0,
hasError: false,
};
const mockExecutions: WorkflowTaskExecution[] = [
{
id: "ex_1",
name: "trigger_1",
type: "webhook",
status: "COMPLETED",
executionTime: 10,
},
{
id: "ex_2",
name: "action_2",
type: "code-js2",
status: "COMPLETED",
executionTime: 200,
},
];
const mockClient = {
get: (url: string) => {
if (url.includes("api/easo/jobs/job_test_1/execution/level/failed")) {
return { json: async () => ({ code: 200, data: { items: [] } }) };
}
if (url.includes("api/easo/jobs/job_test_1/execution")) {
return { json: async () => ({ code: 200, data: mockExecutions }) };
}
if (url.includes("api/easo/jobs/job_test_1")) {
return { json: async () => ({ code: 200, data: mockJob }) };
}
return { json: async () => ({ code: 200, data: null }) };
},
};
const emitted: WorkflowWatchEvent[] = [];
const res = await watchSingleJob(mockClient as any, "job_test_1", {
intervalMs: 50,
timeoutMs: 1000,
onEvent: (ev) => {
emitted.push(ev);
},
});
expect(res.status).toBe("COMPLETED");
expect(res.successCount).toBe(2);
expect(res.hasError).toBe(false);
expect(emitted.length).toBeGreaterThanOrEqual(3); // 2 tasks + 1 job_completed
expect(emitted.some((e) => e.type === "job_completed")).toBe(true);
});
it("watchWorkflowPipeline with once=true inspects the latest job snapshot", async () => {
const mockJobDetail = {
id: "job_recent_1",
pipelineId: "pipe_1",
status: "COMPLETED",
successTaskCount: 1,
errorTaskCount: 0,
};
const mockClient = {
get: (url: string) => {
if (url.includes("api/easo/pipelines/pipe_1/log")) {
return {
json: async () => ({
code: 200,
data: {
jobList: [{ jobId: "job_recent_1", status: "COMPLETED" }],
},
}),
};
}
if (url.includes("api/easo/jobs/running")) {
return { json: async () => ({ code: 200, data: [] }) };
}
if (url.includes("api/easo/jobs/job_recent_1/execution/level/failed")) {
return { json: async () => ({ code: 200, data: { items: [] } }) };
}
if (url.includes("api/easo/jobs/job_recent_1/execution")) {
return {
json: async () => ({
code: 200,
data: [
{
id: "ex_10",
name: "action_clean",
type: "code",
status: "COMPLETED",
executionTime: 50,
},
],
}),
};
}
if (url.includes("api/easo/jobs/job_recent_1")) {
return { json: async () => ({ code: 200, data: mockJobDetail }) };
}
if (url.includes("api/easo/pipelines/pipe_1")) {
return { json: async () => ({ code: 200, data: { id: "pipe_1", label: "测试流水线" } }) };
}
return { json: async () => ({ code: 200, data: null }) };
},
};
const emitted: WorkflowWatchEvent[] = [];
const report = await watchWorkflowPipeline(mockClient as any, "pipe_1", {
once: true,
onEvent: (ev) => {
emitted.push(ev);
},
});
expect(report.totalJobsWatched).toBe(1);
expect(report.hasFailures).toBe(false);
expect(emitted.some((e) => e.type === "pipeline_watch_start")).toBe(true);
expect(emitted.some((e) => e.type === "task_completed" && e.name === "action_clean")).toBe(true);
expect(emitted.some((e) => e.type === "job_completed")).toBe(true);
});
});
});