feat(workflow): implement declarative node editing commands

This commit is contained in:
gitea committed 2026-10-15 16:24:25 +08:00
1 parent 61123ad550
commit 3261b6ebdb
9 files changed
+1415 -6

No files matched your search

+10 -4
View File
@@ -6,10 +6,11 @@ Platform 域负责工作流(EASO/Piper)以及自建应用容器的兼容能
```text
src/domains/platform/
├── types.ts # Zod schema 与类型定义(含 Job 执行树、失败节点、节点日志)
├── api.ts # HTTP 传输层(含 unwrap 空安全校验与 Piper Job 5 大诊断端点)
├── analysis.ts # 工作流静态分析(禁用状态、SKIP 无状态守卫、单据联动覆盖诊断)
└── tools.ts # MCP tool 注册 + 服务层聚合函数
├── types.ts # Zod schema 与类型定义(含 Job 执行树、失败节点、节点日志)
├── api.ts # HTTP 传输层(含 unwrap 空安全校验与 Piper Job 5 大诊断端点)
├── analysis.ts # 工作流静态分析(禁用状态、SKIP 无状态守卫、单据联动覆盖诊断)
├── workflow-nodes.ts # 节点树展平、树形索引定位、声明式增删改与索引重排 SDK
└── tools.ts # MCP tool 注册 + 服务层聚合函数
```
## CLI 常用命令
@@ -27,6 +28,11 @@ 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]
```
## 触发器分类与调测路径分支 (Path Branching)
+3
View File
@@ -940,4 +940,7 @@ export async function getWorkflowSampleData(
return api.getWorkflowSampleData(client, pipelineId, type);
}
export * from "./workflow-nodes.js";
+256
View File
@@ -0,0 +1,256 @@
import { describe, expect, it } from "bun:test";
import {
flattenWorkflowTaskTree,
findWorkflowTask,
reindexTasks,
addWorkflowTask,
editWorkflowTask,
removeWorkflowTask,
buildWorkflowTask,
summarizeTask,
} from "./workflow-nodes.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("触发源节点");
});
});
+448
View File
@@ -0,0 +1,448 @@
import type { WorkflowDetail, WorkflowTask } from "./types.js";
import { NotFoundError, ValidationError } from "../../core/errors.js";
export interface FlattenedWorkflowTask {
task: WorkflowTask;
index: number; // 1-based global sequential index
hierarchicalIndex: string; // e.g. "1", "2.1", "2.1.3"
depth: number;
path: string;
parentName?: string;
summary: string;
}
export interface LocatedWorkflowTask {
task: WorkflowTask;
path: string;
parentTasks: WorkflowTask[];
arrayIndex: number;
hierarchicalIndex: string;
globalIndex: number;
parentName?: string;
}
/**
* 递归计算并生成节点的紧凑配置摘要
*/
export function summarizeTask(task: WorkflowTask): string {
if (task.type === "webhook") {
return task.urlPath ? `urlPath: ${task.urlPath}` : "未配置URL";
}
if (task.type === "clock") {
return `cron: ${task.cron || "0 0 * * *"} (${task.timeZone || "Asia/Shanghai"})`;
}
if (task.type === "code" || task.type === "code-js2") {
const rawCode: string = (task as any).code || "";
const firstLine = rawCode.trim().split("\n")[0] || "";
const len = rawCode.length;
return `脚本 (${len} 字符): ${firstLine.slice(0, 40)}${firstLine.length > 40 ? "..." : ""}`;
}
if (task.type === "http") {
return `${(task as any).method || "POST"} ${(task as any).url || ""}`;
}
if (task.type === "every") {
return `循环遍历: ${(task as any).list || "$item"} (含 ${task.tasks?.length || 0} 个子节点)`;
}
if (task.type === "condition") {
const filters = (task as any).combineFilters?.filters || [];
return `分支条件: ${filters.length} 组规则 (含 ${task.tasks?.length || 0} 个子节点)`;
}
if (task.type === "stop") {
return "阻断终止流程";
}
if (task.type === "ekuaibao-datalink-create-trigger") {
return "业务对象台账新增触发";
}
if (task.type === "ekuaibao-flowform-trigger") {
return "单据流转事件触发";
}
return task.desc || task.label || task.type;
}
/**
* 将整棵工作流任务树展平为有序列表,便于查看与索引
*/
export function flattenWorkflowTaskTree(tasks: WorkflowTask[]): FlattenedWorkflowTask[] {
const result: FlattenedWorkflowTask[] = [];
let globalCounter = 0;
function traverse(
list: WorkflowTask[],
prefix: string,
depth: number,
basePath: string,
parentName?: string
) {
for (let i = 0; i < list.length; i++) {
const task = list[i];
globalCounter += 1;
const hierarchicalIndex = prefix ? `${prefix}.${i + 1}` : `${i + 1}`;
const path = basePath ? `${basePath}.${i}` : `tasks.${i}`;
result.push({
task,
index: globalCounter,
hierarchicalIndex,
depth,
path,
parentName,
summary: summarizeTask(task),
});
if (task.tasks && Array.isArray(task.tasks) && task.tasks.length > 0) {
traverse(task.tasks, hierarchicalIndex, depth + 1, `${path}.tasks`, task.name);
}
}
}
traverse(tasks, "", 0, "tasks");
return result;
}
/**
* 在任务树中按节点名称、层级编号 (如 "2.1") 或全局序号定位目标任务
*/
export function findWorkflowTask(
tasks: WorkflowTask[],
target: string | number
): LocatedWorkflowTask | null {
const targetStr = String(target).trim();
const targetNum = Number(targetStr);
const isNumeric = !Number.isNaN(targetNum) && Number.isInteger(targetNum) && targetNum > 0;
let globalCounter = 0;
function search(
list: WorkflowTask[],
prefix: string,
basePath: string,
parentName?: string
): LocatedWorkflowTask | null {
for (let i = 0; i < list.length; i++) {
const task = list[i];
globalCounter += 1;
const hierarchicalIndex = prefix ? `${prefix}.${i + 1}` : `${i + 1}`;
const path = basePath ? `${basePath}.${i}` : `tasks.${i}`;
const matched =
task.name === targetStr ||
hierarchicalIndex === targetStr ||
(isNumeric && globalCounter === targetNum);
if (matched) {
return {
task,
path,
parentTasks: list,
arrayIndex: i,
hierarchicalIndex,
globalIndex: globalCounter,
parentName,
};
}
if (task.tasks && Array.isArray(task.tasks) && task.tasks.length > 0) {
const found = search(task.tasks, hierarchicalIndex, `${path}.tasks`, task.name);
if (found) return found;
}
}
return null;
}
return search(tasks, "", "tasks");
}
/**
* 递归重算整棵树的 orderIndex 与 levelIndex
*/
export function reindexTasks(
tasks: WorkflowTask[],
parentLevel: number[] = [],
startOrder = 0
): number {
let currentOrder = startOrder;
for (let i = 0; i < tasks.length; i++) {
const task = tasks[i];
task.orderIndex = currentOrder++;
task.levelIndex = [...parentLevel, i];
if (task.tasks && Array.isArray(task.tasks)) {
currentOrder = reindexTasks(task.tasks, task.levelIndex, currentOrder);
}
}
return currentOrder;
}
/**
* 生成规范唯一的合思节点 ID
*/
export function generateNodeName(type: string): string {
const rand = Math.random().toString(36).substring(2, 8);
if (type === "every" || type === "condition") {
return `control_${rand}`;
}
if (type.includes("trigger") || type === "webhook" || type === "clock") {
return `trigger_${rand}`;
}
return `action_${rand}`;
}
export interface AddTaskOptions {
type: string;
label?: string;
code?: string;
desc?: string;
parent?: string | number;
after?: string | number;
extra?: Record<string, any>;
}
/**
* 构建规范的新节点对象
*/
export function buildWorkflowTask(type: string, options: Partial<AddTaskOptions> = {}): WorkflowTask {
const normType = type.trim();
const name = generateNodeName(normType);
switch (normType) {
case "code-js2":
return {
name,
type: "code-js2",
label: options.label || "JS节点(新)",
desc: options.desc || "执行一段JavaScript代码",
groupName: "action",
code: options.code || "// 编写处理逻辑\nreturn items;",
orderIndex: 0,
levelIndex: [0],
status: "active",
...options.extra,
};
case "code":
return {
name,
type: "code",
label: options.label || "代码节点",
desc: options.desc || "执行一段MVEL代码",
groupName: "action",
code: options.code || "return true;",
orderIndex: 0,
levelIndex: [0],
status: "active",
...options.extra,
};
case "http":
return {
name,
type: "http",
label: options.label || "HTTP请求",
groupName: "action",
method: options.extra?.method || "POST",
url: options.extra?.url || "",
header: options.extra?.header || [],
params: options.extra?.params || [],
successCode: options.extra?.successCode || ["200"],
orderIndex: 0,
levelIndex: [0],
status: "active",
...options.extra,
};
case "stop":
return {
name,
type: "stop",
label: options.label || "终止流程",
desc: options.desc || "如果满足条件终止流程",
groupName: "control",
orderIndex: 0,
levelIndex: [0],
status: "active",
...options.extra,
};
case "every":
return {
name,
type: "every",
label: options.label || "依次执行",
desc: options.desc || "依次遍历每个对象",
groupName: "control",
mode: "sequence",
batch: false,
list: options.extra?.list || "@{choose('...$item')}",
filters: [],
tasksMaxLevel: 1,
tasks: [],
orderIndex: 0,
levelIndex: [0],
status: "active",
...options.extra,
};
case "condition":
return {
name,
type: "condition",
label: options.label || "条件分支",
desc: options.desc || "如果满足条件则执行以下动作",
groupName: "control",
combineFilters: options.extra?.combineFilters || { condition: "or", filters: [] },
tasksMaxLevel: 1,
tasks: [],
orderIndex: 0,
levelIndex: [0],
status: "active",
...options.extra,
};
case "webhook":
return {
name,
type: "webhook",
label: options.label || "Webhook触发",
groupName: "trigger",
orderIndex: 0,
levelIndex: [0],
status: "active",
urlPath: crypto.randomUUID(),
params: [],
...options.extra,
};
case "clock":
return {
name,
type: "clock",
label: options.label || "定时触发",
groupName: "trigger",
orderIndex: 0,
levelIndex: [0],
status: "active",
cron: options.extra?.cron || "0 0 * * *",
timeZone: options.extra?.timeZone || "Asia/Shanghai",
...options.extra,
};
default:
return {
name,
type: normType,
label: options.label || `${normType}节点`,
desc: options.desc || "",
groupName: normType.startsWith("control") ? "control" : "action",
orderIndex: 0,
levelIndex: [0],
status: "active",
...options.extra,
};
}
}
/**
* 向工作流声明式追加或插入任务节点
*/
export function addWorkflowTask(
workflow: WorkflowDetail,
options: AddTaskOptions
): { workflow: WorkflowDetail; newTask: WorkflowTask } {
const cloned = JSON.parse(JSON.stringify(workflow)) as WorkflowDetail;
if (!cloned.tasks) cloned.tasks = [];
const newTask = buildWorkflowTask(options.type, options);
if (options.after !== undefined && options.after !== "") {
const target = findWorkflowTask(cloned.tasks, options.after);
if (!target) {
throw new NotFoundError(`未找到插入基准节点 (--after): ${options.after}`);
}
// 插入在该节点的下一个位置
target.parentTasks.splice(target.arrayIndex + 1, 0, newTask);
} else if (options.parent !== undefined && options.parent !== "") {
const parentTarget = findWorkflowTask(cloned.tasks, options.parent);
if (!parentTarget) {
throw new NotFoundError(`未找到父级容器节点 (--parent): ${options.parent}`);
}
if (!parentTarget.task.tasks) parentTarget.task.tasks = [];
parentTarget.task.tasks.push(newTask);
} else {
// 默认追加到顶级 tasks 末尾
cloned.tasks.push(newTask);
}
// 重排索引
reindexTasks(cloned.tasks);
return { workflow: cloned, newTask };
}
export interface EditTaskOptions {
label?: string;
code?: string;
desc?: string;
set?: Record<string, any>;
}
/**
* 定向修改工作流任务节点配置
*/
export function editWorkflowTask(
workflow: WorkflowDetail,
targetKey: string | number,
updates: EditTaskOptions
): { workflow: WorkflowDetail; editedTask: WorkflowTask } {
const cloned = JSON.parse(JSON.stringify(workflow)) as WorkflowDetail;
if (!cloned.tasks) cloned.tasks = [];
const target = findWorkflowTask(cloned.tasks, targetKey);
if (!target) {
throw new NotFoundError(`未找到目标工作流任务节点: ${targetKey}`);
}
const { task } = target;
if (updates.label !== undefined) task.label = updates.label;
if (updates.desc !== undefined) task.desc = updates.desc;
if (updates.code !== undefined) (task as any).code = updates.code;
if (updates.set && typeof updates.set === "object") {
for (const [k, v] of Object.entries(updates.set)) {
(task as any)[k] = v;
}
}
return { workflow: cloned, editedTask: task };
}
/**
* 安全剔除工作流任务节点
*/
export function removeWorkflowTask(
workflow: WorkflowDetail,
targetKey: string | number
): { workflow: WorkflowDetail; removedTask: WorkflowTask } {
const cloned = JSON.parse(JSON.stringify(workflow)) as WorkflowDetail;
if (!cloned.tasks || cloned.tasks.length === 0) {
throw new ValidationError("工作流中无任何任务节点,无法删除");
}
const target = findWorkflowTask(cloned.tasks, targetKey);
if (!target) {
throw new NotFoundError(`未找到待删除的工作流任务节点: ${targetKey}`);
}
// 触发器保护:如果工作流只有首节点且是触发器,或者删除首节点触发器
if (
target.parentTasks === cloned.tasks &&
target.arrayIndex === 0 &&
cloned.tasks.length > 1 &&
(target.task.groupName === "trigger" || target.task.type.includes("trigger") || target.task.type === "webhook" || target.task.type === "clock")
) {
throw new ValidationError(
`节点 [${target.task.name}] (${target.task.label || target.task.type}) 是工作流的触发源节点。直接移除会导致工作流缺少触发器,请使用 workflow save 或在设计器中调整触发器。`
);
}
const [removedTask] = target.parentTasks.splice(target.arrayIndex, 1);
reindexTasks(cloned.tasks);
return { workflow: cloned, removedTask };
}