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

+174
View File
@@ -491,4 +491,178 @@ describe("CLI - workflow job 执行详情与异常精准透视", () => {
expect(parsed.summary.statusDiffCount).toBe(1);
expect(parsed.nodes.find((n: any) => n.taskName === "auto_approve").statusB).toBe("FAILED");
});
it("handles workflow test without pipelineId", async () => {
const res = await handleWorkflowCommand(
{
area: "workflow",
action: "test",
args: [],
options: {},
raw: ["workflow", "test"],
},
mockRuntime
);
expect(res.exitCode).toBe(1);
expect(res.stderr).toContain("用法: hose-use workflow test");
});
it("handles workflow test without --flow by listing candidate sources", async () => {
const mockClient = {
post: (url: string) => ({
json: async () => ({
code: 200,
data: {
type: "flowForm",
total: 1,
label: "我的单据",
items: [
{ id: "ZJ-20261015-001387", title: "资金调拨测试单", flowState: "审批中" },
],
fields: [
{ key: "id", label: "单号" },
{ key: "title", label: "标题" },
],
},
}),
}),
get: (url: string) => {
if (url.includes("platform")) {
return { json: async () => ({ items: [] }) };
}
return { json: async () => ({ code: 200, data: [] }) };
},
};
spies.push(
spyOn(helpers, "createClientsForCorp").mockResolvedValue({
ekbClient: mockClient as any,
easoClient: mockClient as any,
corp: mockCorp,
} as any)
);
spies.push(
spyOn(helpers, "createPiperClientForCorp").mockResolvedValue(mockClient as any)
);
const res = await handleWorkflowCommand(
{
area: "workflow",
action: "test",
args: ["wf_test_1"],
options: { platformId: "p1" },
raw: ["workflow", "test", "wf_test_1", "--platform-id=p1"],
},
mockRuntime
);
expect(res.exitCode).toBe(1);
expect(res.stdout).toContain("未指定测试单号");
expect(res.stdout).toContain("ZJ-20261015-001387");
expect(res.stdout).toContain("资金调拨测试单");
});
it("handles workflow test end-to-end with --flow parameter", async () => {
const mockClient = {
post: (url: string) => {
if (url.includes("debugSource")) {
return {
json: async () => ({
code: 200,
data: {
type: "flowForm",
total: 1,
items: [{ id: "ZJ-20261015-001387", title: "资金调拨", flowState: "审批中" }],
},
}),
};
}
if (url.includes("api/easo/jobs")) {
return {
json: async () => ({
code: 200,
data: "job_debug_888",
}),
};
}
return { json: async () => ({ code: 200, data: null }) };
},
get: (url: string) => {
if (url.includes("execution")) {
return {
json: async () => ({
code: 200,
data: [
{
id: "e1",
name: "trigger_1",
label: "触发器",
type: "ekuaibao-flowform-trigger",
status: "COMPLETED",
executionTime: 10,
},
{
id: "e2",
name: "control_1",
label: "条件节点",
type: "condition",
status: "COMPLETED",
executionTime: 5,
tasks: [{ name: "action_auto", label: "自动审批", type: "http" }],
},
{
id: "e3",
name: "action_stop",
label: "终止节点",
type: "stop",
status: "COMPLETED",
executionTime: 2,
},
],
}),
};
}
return {
json: async () => ({
code: 200,
data: {
id: "job_debug_888",
pipelineId: "wf_test_1",
status: "COMPLETED",
runType: "DEBUG",
durationTime: 17,
},
}),
};
},
};
spies.push(
spyOn(helpers, "createClientsForCorp").mockResolvedValue({
ekbClient: mockClient as any,
easoClient: mockClient as any,
corp: mockCorp,
} as any)
);
spies.push(
spyOn(helpers, "createPiperClientForCorp").mockResolvedValue(mockClient as any)
);
const res = await handleWorkflowCommand(
{
area: "workflow",
action: "test",
args: ["wf_test_1"],
options: { flow: "ZJ-20261015-001387", platformId: "p1" },
raw: ["workflow", "test", "wf_test_1", "--flow=ZJ-20261015-001387", "--platform-id=p1"],
},
mockRuntime
);
expect(res.exitCode).toBe(0);
expect(res.stdout).toContain("工作流自动化调测报告 [wf_test_1]");
expect(res.stdout).toContain("job_debug_888");
expect(res.stdout).toContain("ZJ-20261015-001387");
expect(res.stdout).toContain("control_1");
});
});
+6 -1
View File
@@ -7,6 +7,7 @@ import { handleJob } from "./job.js";
import { handleCheck } from "./check.js";
import { handleAnalyze } from "./analyze.js";
import { handleWorkflowDiff, handleWorkflowDiffJob } from "./diff.js";
import { handleWorkflowTest } from "./test.js";
export async function handleWorkflowCommand(
parsed: CliParsedArgs,
@@ -69,10 +70,14 @@ export async function handleWorkflowCommand(
case "diff-jobs":
case "compare-job":
return handleWorkflowDiffJob(parsed, runtime);
case "test":
case "debug":
case "run-test":
return handleWorkflowTest(parsed, runtime);
default:
return {
stdout: "",
stderr: `未知 workflow 子命令: ${action}。支持: list, get, find, analyze, toggle, publish, patch, save, history, logs, job, diff, diff-job, check\n`,
stderr: `未知 workflow 子命令: ${action}。支持: list, get, find, analyze, toggle, publish, patch, save, history, logs, job, diff, diff-job, check, test, debug\n`,
exitCode: 1,
};
}
+23
View File
@@ -9,6 +9,7 @@ import {
getJobFailedExecutions,
isTaskExecutionFailed,
listPlatforms,
explainConditionBranches,
} from "../../../domains/platform/services.js";
import type { WorkflowTaskExecution } from "../../../domains/platform/types.js";
import { stringOption, numberOption, booleanOption } from "../../parser.js";
@@ -402,6 +403,8 @@ export async function handleJob(parsed: CliParsedArgs, runtime: CliRuntime): Pro
]);
const failedExecutions = await enrichFailedExecutions(client, jobId, failedPage.items);
const conditionDiagnoses = explainConditionBranches(tree);
if (runtime.jsonMode) {
return {
stdout: printJson(
@@ -410,6 +413,7 @@ export async function handleJob(parsed: CliParsedArgs, runtime: CliRuntime): Pro
job,
executionTree: tree,
failedExecutions,
conditionDiagnoses,
},
runtime.outputOptions
),
@@ -473,6 +477,25 @@ export async function handleJob(parsed: CliParsedArgs, runtime: CliRuntime): Pro
);
}
if (conditionDiagnoses.length > 0) {
outLines.push("");
outLines.push("── 💡 条件分支跳过诊断 (为什么没有走内部子任务?) ──");
for (const diag of conditionDiagnoses) {
outLines.push(` ⚠️ [${diag.conditionNodeName}] ${diag.conditionNodeLabel} (Execution ID: ${diag.conditionNodeId})`);
outLines.push(` • 判定结论: ${diag.summary}`);
outLines.push(` • 未执行子任务: ${diag.skippedTaskNames.join(", ")}`);
if (diag.rules.length > 0) {
outLines.push(" • 规则比对明细:");
for (const r of diag.rules) {
const statusIcon = r.matched ? "✅" : "❌";
const missTag = r.isMissing ? " [⚠️ 属性缺失]" : "";
outLines.push(` ${statusIcon} ${r.leftLabel} ${r.operatorLabel} ${JSON.stringify(r.expectedValue)}${missTag}`);
outLines.push(` ↳ ${r.detail}`);
}
}
}
}
return {
stdout: `${outLines.join("\n")}\n`,
stderr: "",
+9 -2
View File
@@ -17,8 +17,15 @@ export async function createWorkflowDetailClient(
const explicit = stringOption(parsed.options, PLATFORM_ID_OPTION_KEYS);
let platformId = explicit;
if (!platformId) {
const all = await listAllWorkflows(clients, { page: 1, pageSize: 100 });
platformId = all.workflows.find((workflow) => workflow.id === pipelineId)?.platformId;
try {
const corpId = runtime.selectedCorp!.corpId || runtime.selectedCorp!.id;
const { listPlatforms } = await import("../../../domains/platform/services.js");
const platforms = await listPlatforms(clients.ekbClient, corpId);
const firstActive = platforms.find((p) => p.active) ?? platforms[0];
platformId = firstActive?.id;
} catch {
// Fall back to easoClient
}
}
return {
client: platformId ? await createPiperClientForCorp(runtime.selectedCorp!, platformId) : clients.easoClient,
+135
View File
@@ -0,0 +1,135 @@
import {
getWorkflowDebugSource,
runWorkflowDebugTest,
} from "../../../domains/platform/services.js";
import { stringOption, booleanOption, numberOption } from "../../parser.js";
import { printJson, printTable, printKeyValue } from "../../printer.js";
import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js";
import { createWorkflowDetailClient } from "./shared.js";
export async function handleWorkflowTest(
parsed: CliParsedArgs,
runtime: CliRuntime
): Promise<CliResult> {
const pipelineId = parsed.args[0] || stringOption(parsed.options, ["id", "pipeline-id", "pipelineId"]);
if (!pipelineId) {
return {
stdout: "",
stderr: "用法: hose-use workflow test <pipelineId> --flow=<单号|单据ID> [--auto-publish] [--timeout=<ms>]\n别名: hose-use workflow debug <pipelineId> --flow=<单号>\n",
exitCode: 1,
};
}
const { client } = await createWorkflowDetailClient(parsed, runtime, pipelineId);
const flowCodeOrId = stringOption(parsed.options, ["flow", "code", "flow-code", "flowCode", "bill", "entity", "id"]);
const autoPublish = booleanOption(parsed.options, ["auto-publish", "autoPublish", "publish"]);
const timeoutMs = numberOption(parsed.options, ["timeout", "timeout-ms", "timeoutMs"]) || 15000;
// 如果没有传入 --flow,先列出当前可用的调试数据源供用户参考
if (!flowCodeOrId) {
try {
const source = await getWorkflowDebugSource(client, pipelineId, { page: 1, pageSize: 5 });
if (runtime.jsonMode) {
return {
stdout: printJson(source, runtime.outputOptions),
stderr: "",
exitCode: 0,
};
}
const rows = source.items.map((it, idx) => [
idx + 1,
it.id,
it.title || "-",
it.flowState || "-",
]);
const out = [
`⚠️ 未指定测试单号,请通过 --flow=<单号> 传入测试单据。`,
"",
`── 工作流 [${pipelineId}] 最近可用测试数据源 (${source.label || "候选单据"}) ──`,
rows.length ? printTable(["#", "单据编号 (ID)", "单据名称 (Title)", "状态 (Status)"], rows) : "暂无可用测试单据",
"",
`示例: hose-use workflow test ${pipelineId} --flow=${source.items[0]?.id || "ZJ-xxxx"}`,
].join("\n");
return { stdout: `${out}\n`, stderr: "", exitCode: 1 };
} catch (err: any) {
return {
stdout: "",
stderr: `未指定测试单号 (--flow=<单号>),且拉取候选单据失败: ${err.message || String(err)}\n`,
exitCode: 1,
};
}
}
// 执行端到端调试测试
const report = await runWorkflowDebugTest(client, pipelineId, {
flowCodeOrId,
autoPublish,
timeoutMs,
});
if (runtime.jsonMode) {
return {
stdout: printJson(report, runtime.outputOptions),
stderr: "",
exitCode: 0,
};
}
const treeRows = report.executionTree.map((node, idx) => [
idx + 1,
node.id,
node.name || "-",
node.label || (node as any).displayName || "-",
node.type || "-",
node.status || "-",
String((node as any).durationTime ?? node.executionTime ?? "-"),
node.error?.message || "-",
]);
const outLines = [
`====== 工作流自动化调测报告 [${pipelineId}] ======`,
printKeyValue({
"工作流 ID (pipelineId)": pipelineId,
"生成 Job ID": report.jobId,
"测试目标单据": report.targetEntityId,
"执行结果状态": report.status,
"运行模式": report.runType,
"总耗时(ms)": String(report.durationTime ?? "-"),
"节点执行总数": report.executionTree.length,
"异常/跳过节点数": report.failedExecutions.length,
}),
"",
"── 顶层节点执行树 ──",
treeRows.length
? printTable(
["#", "Execution ID", "节点标识 (name)", "节点名称", "类型 (type)", "状态 (status)", "耗时(ms)", "错误信息"],
treeRows
)
: "暂无顶层节点执行记录",
];
if (report.conditionDiagnoses.length > 0) {
outLines.push("");
outLines.push("── 💡 条件分支跳过诊断 (为什么没有走内部子任务?) ──");
for (const diag of report.conditionDiagnoses) {
outLines.push(` ⚠️ [${diag.conditionNodeName}] ${diag.conditionNodeLabel} (Execution ID: ${diag.conditionNodeId})`);
outLines.push(` • 判定结论: ${diag.summary}`);
outLines.push(` • 未执行子任务: ${diag.skippedTaskNames.join(", ")}`);
if (diag.rules.length > 0) {
outLines.push(" • 规则比对明细:");
for (const r of diag.rules) {
const statusIcon = r.matched ? "✅" : "❌";
const missTag = r.isMissing ? " [⚠️ 属性缺失]" : "";
outLines.push(` ${statusIcon} ${r.leftLabel} ${r.operatorLabel} ${JSON.stringify(r.expectedValue)}${missTag}`);
outLines.push(` ↳ ${r.detail}`);
}
}
}
}
return {
stdout: `${outLines.join("\n")}\n`,
stderr: "",
exitCode: report.status === "FAILED" ? 1 : 0,
};
}
+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;
}