feat(workflow): add end-to-end workflow debug test command and condition branch explanation

This commit is contained in:
gitea committed 2026-10-15 13:24:14 +08:00
1 parent 26a6b7318c
commit fe6183dd44
13 files changed
+1026 -3

No files matched your search

+2
View File
@@ -22,6 +22,8 @@ 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=<单号|单据ID> [--auto-publish]
hose-use workflow debug <pipelineId> --flow=<单号>
```
## 详细文档
+54
View File
@@ -111,4 +111,58 @@ describe("Workflow static analysis", () => {
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");
});
});
+42
View File
@@ -66,6 +66,12 @@ const KNOWN_TYPES = new Set([
"ekuaibao-datalink-create",
"ekuaibao-datalink-edit",
"ekuaibao-datalink-delete",
"ekuaibao-flowform-trigger",
"ekuaibao-ebot-trigger",
"ekuaibao-datalink-create-trigger",
"ekuaibao-datalink-time-trigger",
"ekuaibao-datalink-edit-trigger",
"ekuaibao-datalink-delete-trigger",
"data-convert",
"flow-create-task",
]);
@@ -380,6 +386,42 @@ export function analyzeWorkflow(
}
}
// 诊断 4: 触发器节点配置了无效的单据审批状态过滤 (DEADLOCK_TRIGGER_STATE_FILTER)
if (
(task.type === "ekuaibao-flowform-trigger" || task.type === "ekuaibao-ebot-trigger") &&
(task as Record<string, unknown>).combineFilters
) {
const rawFilters = JSON.stringify((task as Record<string, unknown>).combineFilters);
if (
rawFilters.includes('"key":"state"') &&
(rawFilters.includes('"APPROVING"') || rawFilters.includes('"approving"'))
) {
diagnostics.push({
severity: "error",
code: "DEADLOCK_TRIGGER_STATE_FILTER",
path,
message: `触发器节点 [${task.label || task.name}] (${task.name}) 配置了 state == APPROVING 状态过滤条件。合思单据审批出站事件属于动作事件(如 backlog.approving),事件载荷中不携带大写 APPROVING 状态字段,该过滤会导致出站事件被 100% 静默丢弃,下游审批流程永久无法触发!建议移除 state 过滤,改用后置条件节点判断审批人。`,
});
}
}
// 诊断 5: HTTP 自动审批节点 URL 与中括号校验 (MISSING_BACKLOG_DATA_BRACKETS)
if (task.type === "http") {
const url = String((task as Record<string, unknown>).url || "");
if (url.includes("api/openapi/v1/backlog/data")) {
const match = url.match(/api\/openapi\/v1\/backlog\/data\/([^?#]+)/);
const segment = match ? match[1] : "";
if (segment && (!segment.startsWith("[") || !segment.includes("]"))) {
diagnostics.push({
severity: "warning",
code: "MISSING_BACKLOG_DATA_BRACKETS",
path,
message: `HTTP 自动审批节点 [${task.label || task.name}] 的 URL 路径参数缺少合思 OpenAPI 规范的方括号(规范要求: /api/openapi/v1/backlog/data/[{flowId}]),缺少方括号将导致服务端直接返回 404 Not Found。`,
});
}
}
}
visit(task.tasks || [], path, insideEvery || task.type === "every");
});
};
+41
View File
@@ -19,6 +19,7 @@ import {
StaffSchema,
WebhookInfoSchema,
WorkflowSampleDataSchema,
WorkflowDebugSourceResultSchema,
} from "./types.js";
import type { WorkflowState } from "./types.js";
@@ -325,3 +326,43 @@ export async function sampleWorkflowData(
return WorkflowSampleDataSchema.parse(await response.json());
}
// ── 调试数据源与发起调试(Piper)─────────────────────────────────────────────
export async function getWorkflowDebugSource(
client: KyInstance,
pipelineId: string,
options: { page?: number; pageSize?: number; keywords?: string } = {}
): Promise<import("./types.js").WorkflowDebugSourceResult> {
const response = await client.post(`api/easo/pipelines/${pipelineId}/debugSource`, {
json: {
number: options.page ?? 1,
pageSize: options.pageSize ?? 20,
...(options.keywords ? { keywords: options.keywords } : {}),
},
});
return unwrap(response, WorkflowDebugSourceResultSchema);
}
export async function triggerWorkflowDebug(
client: KyInstance,
pipelineId: string,
options: { entityId: string; autoPublish?: boolean; dataLimit?: number }
): Promise<string> {
const response = await client.post("api/easo/jobs", {
json: {
pipelineId,
inputs: {
id: options.entityId,
$autoPublish: options.autoPublish ?? false,
},
dataLimit: options.dataLimit ?? 20,
},
});
const data = await unwrap(response, z.union([z.string(), z.number(), z.record(z.string(), z.any())]));
if (typeof data === "string") return data;
if (typeof data === "number") return String(data);
if (data && typeof data === "object" && "id" in data) return String(data.id);
if (data && typeof data === "object" && "jobId" in data) return String(data.jobId);
return String(data);
}
+101
View File
@@ -1,6 +1,7 @@
import { KyInstance } from "ky";
import { CorpConfig } from "../../core/config/types.js";
import * as api from "./api.js";
import { explainConditionBranches } from "./workflow-branch.js";
import {
Platform,
WorkflowSummary,
@@ -645,3 +646,103 @@ export function diffWorkflowJobs(
};
}
export function getWorkflowDebugSource(...args: Parameters<typeof api.getWorkflowDebugSource>) {
return api.getWorkflowDebugSource(...args);
}
export function triggerWorkflowDebug(...args: Parameters<typeof api.triggerWorkflowDebug>) {
return api.triggerWorkflowDebug(...args);
}
export async function runWorkflowDebugTest(
client: import("ky").KyInstance,
pipelineId: string,
options: {
flowCodeOrId: string;
autoPublish?: boolean;
timeoutMs?: number;
pollIntervalMs?: number;
}
): Promise<import("./types.js").WorkflowTestReport> {
let targetEntityId = options.flowCodeOrId;
const isDirectCode = options.flowCodeOrId.includes("-") || options.flowCodeOrId.startsWith("ID01");
if (!isDirectCode) {
try {
const source = await api.getWorkflowDebugSource(client, pipelineId, {
page: 1,
pageSize: 10,
keywords: options.flowCodeOrId,
});
const matched = source.items.find(
(item) => item.id === options.flowCodeOrId || item.title.includes(options.flowCodeOrId)
);
if (matched) {
targetEntityId = matched.id;
}
} catch {
// 关键字搜索超时或失败时直接回退使用传入值
}
}
const jobId = await api.triggerWorkflowDebug(client, pipelineId, {
entityId: targetEntityId,
autoPublish: options.autoPublish ?? false,
});
const timeoutMs = options.timeoutMs ?? 15000;
const pollIntervalMs = options.pollIntervalMs ?? 500;
const start = Date.now();
let finalJob: import("./types.js").WorkflowJobDetail | undefined;
while (Date.now() - start < timeoutMs) {
try {
const job = await api.getJob(client, jobId);
const state = (job.status || (job as any).state || "").toUpperCase();
if (state === "COMPLETED" || state === "FAILED" || state === "STOP") {
finalJob = job;
break;
}
} catch {
// 任务刚创建可能存在短延时,继续轮询
}
await new Promise((resolve) => setTimeout(resolve, pollIntervalMs));
}
if (!finalJob) {
finalJob = await api.getJob(client, jobId);
}
const [tree, failedPage] = await Promise.all([
api.getJobExecutionTree(client, jobId).catch(() => []),
api.getJobFailedExecutions(client, jobId).catch(() => ({
number: 1,
size: 100,
totalPages: 0,
totalItems: 0,
items: [],
})),
]);
const rawFailed = extractFailureExecutions(tree, failedPage.items);
const conditionDiagnoses = explainConditionBranches(tree);
return {
jobId,
pipelineId,
status: finalJob.status || (finalJob as any).state || "UNKNOWN",
runType: finalJob.runType || "DEBUG",
durationTime: typeof (finalJob as any).durationTime === "number" ? (finalJob as any).durationTime : undefined,
targetEntityId,
executionTree: tree,
failedExecutions: rawFailed,
conditionDiagnoses,
};
}
export {
explainConditionBranches,
type ConditionBranchExplanation,
type ConditionRuleExplanation,
} from "./workflow-branch.js";
+35
View File
@@ -604,4 +604,39 @@ export interface WorkflowJobDiff {
};
}
// ── 调试数据源与测试结果 ───────────────────────────────────────────────────────
export const WorkflowDebugSourceItemSchema = z
.object({
id: z.string(),
title: z.string().default(""),
flowState: z.string().default(""),
})
.passthrough();
export const WorkflowDebugSourceResultSchema = z
.object({
type: z.string().default(""),
total: z.number().default(0),
items: z.array(WorkflowDebugSourceItemSchema).default([]),
fields: z.array(z.object({ key: z.string(), label: z.string() })).default([]),
label: z.string().default(""),
})
.passthrough();
export type WorkflowDebugSourceItem = z.infer<typeof WorkflowDebugSourceItemSchema>;
export type WorkflowDebugSourceResult = z.infer<typeof WorkflowDebugSourceResultSchema>;
export interface WorkflowTestReport {
jobId: string;
pipelineId: string;
status: string;
runType: string;
durationTime?: number;
targetEntityId: string;
executionTree: WorkflowTaskExecution[];
failedExecutions: WorkflowTaskExecution[];
conditionDiagnoses: import("./workflow-branch.js").ConditionBranchExplanation[];
}
@@ -0,0 +1,141 @@
import { describe, expect, it } from "bun:test";
import { explainConditionBranches } from "./workflow-branch.js";
import type { WorkflowTaskExecution } from "./types.js";
describe("Workflow Condition Branch Diagnosis", () => {
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);
});
});
+263
View File
@@ -0,0 +1,263 @@
import type { WorkflowTaskExecution } from "./types.js";
export interface ConditionRuleExplanation {
leftLabel: string;
upstreamNode: string;
upstreamProp: string;
operator: string;
operatorLabel: string;
expectedValue: any;
actualValue: any;
isMissing: boolean;
matched: boolean;
detail: string;
}
export interface ConditionBranchExplanation {
conditionNodeId: string;
conditionNodeName: string;
conditionNodeLabel: string;
hasSkippedTasks: boolean;
skippedTaskNames: string[];
rules: ConditionRuleExplanation[];
summary: string;
}
const OP_MAP: Record<string, string> = {
eq: "等于",
neq: "不等于",
include: "包含",
not_include: "不包含",
in: "在列表中",
not_in: "不在列表中",
gt: "大于",
gte: "大于等于",
lt: "小于",
lte: "小于等于",
empty: "为空",
not_empty: "不为空",
};
/**
* 尝试从 @{choose('...')} 标签中提取上游节点名、属性名与可读标签
*/
function parseChooseTag(tag: string): {
upstreamNode: string;
upstreamProp: string;
label: string;
} | null {
if (typeof tag !== "string") return null;
const match = tag.match(/@\{choose\('(.*)'\)\}/);
if (!match) return null;
try {
const parsed = JSON.parse(match[1]);
const upstreamNode = parsed.key || "";
const upstreamProp = parsed.properties?.[0]?.key || "";
const label = parsed.label || `${upstreamNode}.${upstreamProp}`;
return { upstreamNode, upstreamProp, label };
} catch {
return null;
}
}
/**
* 尝试从 @{value('...')} 中提取人类可读值
*/
function parseValueTag(val: any): any {
if (Array.isArray(val)) {
return val.map((v) => parseValueTag(v));
}
if (typeof val === "string") {
const match = val.match(/@\{value\('(.*)'\)\}/);
if (match) {
try {
const parsed = JSON.parse(match[1]);
return parsed.label ? `${parsed.label} (${parsed.key})` : parsed.key || parsed.value;
} catch {
return val;
}
}
}
return val;
}
/**
* 比较两个值是否匹配
*/
function evaluateRule(actual: any, expected: any, compare: string): boolean {
if (actual === undefined || actual === null) {
if (compare === "empty") return true;
if (compare === "not_empty") return false;
return false;
}
const actualStr = String(actual);
const expectedStr = typeof expected === "string" ? expected : JSON.stringify(expected);
switch (compare) {
case "eq":
if (Array.isArray(actual)) {
if (Array.isArray(expected)) {
return JSON.stringify(actual) === JSON.stringify(expected);
}
return actual.length === 1 && String(actual[0]) === expectedStr;
}
return actualStr === expectedStr;
case "neq":
return actualStr !== expectedStr;
case "include":
if (Array.isArray(actual)) {
return actual.some((item) => String(item).includes(expectedStr) || expectedStr.includes(String(item)));
}
return actualStr.includes(expectedStr);
case "not_include":
if (Array.isArray(actual)) {
return !actual.some((item) => String(item).includes(expectedStr));
}
return !actualStr.includes(expectedStr);
case "empty":
return Array.isArray(actual) ? actual.length === 0 : !actual;
case "not_empty":
return Array.isArray(actual) ? actual.length > 0 : Boolean(actual);
default:
return actualStr === expectedStr;
}
}
/**
* 分析 Job 执行树中的条件节点,诊断分支是否跳过及跳过的具体字段原因
*/
export function explainConditionBranches(
tree: WorkflowTaskExecution[]
): ConditionBranchExplanation[] {
const nodeMap = new Map<string, WorkflowTaskExecution>();
const executedNames = new Set<string>();
for (const node of tree) {
if (node.name) {
nodeMap.set(node.name, node);
executedNames.add(node.name);
}
if (node.id) {
nodeMap.set(node.id, node);
}
}
const explanations: ConditionBranchExplanation[] = [];
for (const node of tree) {
const rawNode = node as Record<string, any>;
if (rawNode.type !== "condition") continue;
const childTasks = Array.isArray(rawNode.tasks) ? rawNode.tasks : [];
if (childTasks.length === 0) continue;
// 检查子任务是否执行过
const childNames = childTasks.map((t: any) => t.name || t.id).filter(Boolean);
const anyExecuted = childNames.some((name: string) => executedNames.has(name));
if (anyExecuted) {
// 子分支正常执行,无需诊断跳过
continue;
}
const skippedTaskNames = childTasks.map((t: any) => `${t.name || t.id} (${t.label || t.displayName || t.type})`);
const rules: ConditionRuleExplanation[] = [];
// 解析 combineFilters
const rawFilters = rawNode.combineFilters?.filters;
if (Array.isArray(rawFilters)) {
for (const group of rawFilters) {
const subFilters = Array.isArray(group.filters) ? group.filters : [group];
for (const f of subFilters) {
const chooseInfo = parseChooseTag(f.key);
const rawExpected = f.value;
const parsedExpected = parseValueTag(rawExpected);
const op = f.compare || "eq";
const opLabel = OP_MAP[op] || op;
let upstreamNode = "";
let upstreamProp = "";
let leftLabel = String(f.key);
if (chooseInfo) {
upstreamNode = chooseInfo.upstreamNode;
upstreamProp = chooseInfo.upstreamProp;
leftLabel = chooseInfo.label;
} else if (typeof f.key === "string") {
upstreamProp = f.key;
}
// 从上游节点提取真实 outputs
const upstreamExecution = upstreamNode ? nodeMap.get(upstreamNode) : undefined;
const upstreamOutputs = upstreamExecution?.output ?? (upstreamExecution as any)?.outputs;
let actualVal: any = undefined;
let isMissing = false;
if (upstreamOutputs && typeof upstreamOutputs === "object") {
if (upstreamProp in upstreamOutputs) {
actualVal = upstreamOutputs[upstreamProp];
} else {
isMissing = true;
}
} else if (upstreamExecution) {
isMissing = true;
}
// 提取纯净 ID 比对
let cleanExpected = rawExpected;
if (typeof rawExpected === "string" && rawExpected.includes("@{value(")) {
const m = rawExpected.match(/"key":"([^"]+)"/);
if (m) cleanExpected = m[1];
} else if (Array.isArray(rawExpected) && rawExpected.length > 0 && typeof rawExpected[0] === "string") {
const m = rawExpected[0].match(/"key":"([^"]+)"/);
if (m) cleanExpected = m[1];
}
const matched = evaluateRule(actualVal, cleanExpected, op);
let detail = "";
if (isMissing) {
const availableKeys = upstreamOutputs ? Object.keys(upstreamOutputs).join(", ") : "无出参";
detail = `上游节点 [${upstreamNode}] 未返回该属性 [${upstreamProp}](字段名可能脱节,上游可用字段: ${availableKeys})➔ 解析值为 null`;
} else {
const actStr = typeof actualVal === "object" ? JSON.stringify(actualVal) : String(actualVal ?? "null");
const expStr = typeof parsedExpected === "object" ? JSON.stringify(parsedExpected) : String(parsedExpected);
detail = `实际值: ${actStr} 与期望值 [${expStr}] 比对结果为 ${matched ? "True" : "False"}`;
}
rules.push({
leftLabel,
upstreamNode,
upstreamProp,
operator: op,
operatorLabel: opLabel,
expectedValue: parsedExpected,
actualValue: actualVal,
isMissing,
matched,
detail,
});
}
}
}
let summary = `条件判定未通过 (False),子任务 [${skippedTaskNames.join(", ")}] 被跳过未执行`;
const missingRule = rules.find((r) => r.isMissing);
if (missingRule) {
summary = `条件字段脱节: 上游节点 [${missingRule.upstreamNode}] 缺少属性 [${missingRule.upstreamProp}],判定为 False,子任务被跳过`;
}
explanations.push({
conditionNodeId: node.id,
conditionNodeName: node.name || "-",
conditionNodeLabel: node.label || (node as any).displayName || "条件节点",
hasSkippedTasks: true,
skippedTaskNames,
rules,
summary,
});
}
return explanations;
}