feat(workflow): 准确识别工作流延时执行与在途运行状态并补全节点字典

This commit is contained in:
gitea committed 2026-10-21 17:21:35 +08:00
1 parent 36a4d3b27b
commit aea30fbcd5
15 files changed
+615 -78

No files matched your search

+83 -12
View File
@@ -1,4 +1,4 @@
import { listWorkflowLogs, listWorkflowSnapshots } from "../../../domains/platform/services.js";
import { getWorkflowDetail, listWorkflowLogs, listWorkflowSnapshots } from "../../../domains/platform/services.js";
import { stringOption, numberOption, booleanOption } from "../../parser.js";
import { printJson, printTable, printKeyValue } from "../../printer.js";
import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js";
@@ -37,46 +37,117 @@ export async function handleLogs(parsed: CliParsedArgs, runtime: CliRuntime): Pr
startTime: stringOption(parsed.options, ["start-time", "startTime"]),
endTime: stringOption(parsed.options, ["end-time", "endTime"]),
});
const stateOption = stringOption(parsed.options, ["state"]);
const hasErrorFilter = booleanOption(parsed.options, ["has-error", "hasError", "errors"]);
const isJobError = (job: any): boolean => {
const s = (job.status || "").toUpperCase();
if (s === "STARTED" || s === "RUNNING") return false;
if (job.hasError === true || job.hasError === "存在" || job.hasError === "true") return true;
if (typeof job.errorTaskCount === "number" && job.errorTaskCount > 0) return true;
if (job.state === "FAILED" || job.status === "FAILED") return true;
return false;
};
const filteredJobList = hasErrorFilter
? rawResult.jobList.filter(isJobError)
: rawResult.jobList;
const result = hasErrorFilter
? { ...rawResult, jobList: filteredJobList }
: rawResult;
if (runtime.jsonMode) return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
let filteredJobList = rawResult.jobList;
if (hasErrorFilter) {
filteredJobList = filteredJobList.filter(isJobError);
} else if (stateOption) {
const norm = stateOption.trim().toUpperCase();
if (norm === "FAILED" || norm === "FAIL" || norm === "ERROR") {
filteredJobList = filteredJobList.filter(isJobError);
} else if (norm === "COMPLETED" || norm === "SUCCESS") {
filteredJobList = filteredJobList.filter((j: any) => (j.status || "").toUpperCase() === "COMPLETED" && !isJobError(j));
} else if (norm === "RUNNING" || norm === "STARTED" || norm === "IN_PROGRESS") {
filteredJobList = filteredJobList.filter((j: any) => {
const s = (j.status || "").toUpperCase();
return s === "STARTED" || s === "RUNNING";
});
}
}
const inProgressCount = Math.max(
0,
(rawResult.executeCount ?? 0) - (rawResult.successCount ?? 0) - (rawResult.errorCount ?? 0)
);
const result = {
...rawResult,
jobList: filteredJobList,
inProgressCount,
};
let workflowName = rawResult.jobList[0]?.jobName;
let workflowState: string | undefined;
try {
const detail = await getWorkflowDetail(client, pipelineId);
if (detail) {
workflowName = detail.pipelineName || detail.label || workflowName;
workflowState = detail.state === 1 ? "🟢 启用中" : "⚪ 已停用";
}
} catch {}
if (runtime.jsonMode) {
return {
stdout: printJson({ ...result, workflowName, workflowState }, runtime.outputOptions),
stderr: "",
exitCode: 0,
};
}
const formatRunType = (runType?: string): string => {
if (!runType) return "-";
const upper = runType.toUpperCase();
if (upper === "DEBUG") return "🧪 调试";
if (upper === "RUN") return "🏃 运行";
return runType;
};
const formatJobStatus = (status?: string, state?: unknown): string => {
const s = (status || "").toUpperCase();
if (s === "STARTED" || s === "RUNNING") return "⏳ 运行中";
if (s === "COMPLETED" || s === "SUCCESS") return "✅ 已完成";
if (s === "FAILED" || s === "ERROR") return "❌ 失败";
if (s === "STOP" || s === "STOPPED") return "🛑 终止";
if (s === "CANCELLED" || s === "CANCELED") return "🚫 取消";
if (!s && (state === 0 || state === "0")) return "COMPLETED";
return s || String(state ?? "-");
};
const formatErrorColumn = (job: any): string => {
const s = (job.status || "").toUpperCase();
if (s === "STARTED" || s === "RUNNING") return "⏳ 执行中";
if (isJobError(job)) return "⚠️ 包含错误";
return "正常";
};
const rows = result.jobList.map((job: any, idx) => [
idx + 1,
job.jobId || job.id || "-",
job.status || (job.state === 0 ? "COMPLETED" : String(job.state ?? "-")),
formatRunType(job.runType),
formatJobStatus(job.status, job.state),
job.successTaskCount ?? 0,
job.errorTaskCount ?? 0,
isJobError(job) ? "⚠️ 包含错误" : "正常",
formatErrorColumn(job),
job.durationTime ?? "-",
job.executeTime || job.startTime || "-",
]);
const tableStr = rows.length
? printTable(
["#", "Job ID", "状态 (state)", "成功节点 (successTaskCount)", "失败节点 (errorTaskCount)", "有错误 (hasError)", "耗时(ms)", "开始时间"],
["#", "Job ID", "类型 (runType)", "状态 (state)", "成功节点", "失败节点", "有错误", "耗时(ms)", "开始时间"],
rows
)
: "暂无匹配的运行记录";
return {
stdout: [
`====== 工作流运行日志 [${pipelineId}] ======`,
`====== 工作流运行日志 [${pipelineId}]${workflowName ? ` · ${workflowName}` : ""}${workflowState ? ` (${workflowState})` : ""} ======`,
printKeyValue({
...(workflowName ? { "工作流名称": workflowName } : {}),
...(workflowState ? { "当前状态": workflowState } : {}),
"执行次数": result.executeCount,
"成功次数": result.successCount,
"错误次数": result.errorCount,
...(result.inProgressCount > 0 ? { "运行中/延时": `${result.inProgressCount} (正在执行或延时等待中)` } : {}),
"日志条数": result.totalItems,
"当前返回记录": result.jobList.length,
}),
+146 -13
View File
@@ -7,6 +7,7 @@ import {
getJobExecutionLevel,
getJobExecutionTree,
getJobFailedExecutions,
getWorkflowDetail,
isTaskExecutionFailed,
listPlatforms,
explainConditionBranches,
@@ -119,6 +120,7 @@ export async function handleJob(parsed: CliParsedArgs, runtime: CliRuntime): Pro
const nodeQuery = stringOption(parsed.options, ["node", "task", "node-id", "nodeId"]);
const onlyFailed = booleanOption(parsed.options, ["failed", "fail", "errors"]);
const verbose = booleanOption(parsed.options, ["verbose", "v"]);
const isTimeline = booleanOption(parsed.options, ["timeline", "progress", "steps"]);
// 1. --logs=<executionId>
if (logsExecutionId) {
@@ -389,7 +391,7 @@ export async function handleJob(parsed: CliParsedArgs, runtime: CliRuntime): Pro
};
}
// 4. Default mode: Job overview + top-level tree + failed executions
// 4. Default mode: Job overview + top-level tree + failed executions + timeline
const [job, tree, failedPage] = await Promise.all([
getJob(client, jobId),
getJobExecutionTree(client, jobId),
@@ -401,19 +403,120 @@ export async function handleJob(parsed: CliParsedArgs, runtime: CliRuntime): Pro
items: [] as WorkflowTaskExecution[],
})),
]);
const workflowDetail = await getWorkflowDetail(client, job.pipelineId).catch(() => undefined);
const failedExecutions = await enrichFailedExecutions(client, jobId, failedPage.items);
const conditionDiagnoses = explainConditionBranches(tree);
const timeline = workflowDetail?.tasks?.map((t: any, idx: number) => {
const executed = tree.find((node) => node.name === t.name);
let statusText = "⏳ 未执行";
let errorDetail = "-";
if (executed) {
if (executed.status === "COMPLETED") statusText = "✅ 已完成";
else if (executed.status === "FAILED") {
statusText = "❌ 失败中断";
const msg = (executed.error?.message || "执行失败").replace(/\s+/g, " ");
errorDetail = msg.length > 100 ? `${msg.slice(0, 97)}...` : msg;
} else if (executed.status === "STARTED" || executed.status === "RUNNING") {
statusText = t.type === "task-dynamic-delay" ? "⏳ 延时等待中" : "⏳ 正在执行中";
} else {
statusText = executed.status;
}
} else {
const runningPrior = tree.find((node) => node.status === "STARTED" || node.status === "RUNNING");
const failedPrior = tree.find((node) => node.status === "FAILED");
if (runningPrior) {
statusText = "⏳ 等待前序步骤执行完成";
} else if (failedPrior) {
statusText = "⏳ 未执行 (因前序步骤中断)";
}
}
return {
index: idx + 1,
name: t.name,
displayName: t.displayName || t.label || t.name,
type: t.type,
status: statusText,
duration: executed ? String((executed as any).durationTime ?? executed.executionTime ?? "-") : "-",
detail: errorDetail,
};
});
if (isTimeline && timeline && timeline.length > 0) {
if (runtime.jsonMode) {
return {
stdout: printJson(
{
jobId,
pipelineId: job.pipelineId,
workflowName: workflowDetail?.pipelineName || workflowDetail?.label,
workflowState: workflowDetail?.state === 1 ? "🟢 启用中" : "⚪ 已停用",
jobStatus: job.state ?? job.status,
totalTasks: timeline.length,
executedTasks: tree.length,
unexecutedTasks: timeline.length - tree.length,
timeline,
},
runtime.outputOptions
),
stderr: "",
exitCode: 0,
};
}
const timelineRows = timeline.map((it: any) => [
it.index,
it.name,
it.displayName,
it.type,
it.status,
it.duration,
it.detail,
]);
return {
stdout: [
`====== 工作流全链路步骤进度 [${job.id}] ======`,
printKeyValue({
"Job ID": job.id,
"工作流 ID": job.pipelineId,
...(workflowDetail ? { "工作流名称": workflowDetail.pipelineName || workflowDetail.label } : {}),
"工作流状态": workflowDetail?.state === 1 ? "🟢 启用中" : "⚪ 已停用",
"Job 状态": job.state ?? job.status,
"定义总步骤数": timeline.length,
"已调度步骤数": tree.length,
"未执行步骤数": timeline.length - tree.length,
}),
"",
printTable(
["#", "节点标识", "步骤名称", "类型", "执行状态", "耗时(ms)", "详细说明"],
timelineRows
),
"",
].join("\n"),
stderr: "",
exitCode: 0,
};
}
if (runtime.jsonMode) {
return {
stdout: printJson(
{
jobId,
job,
workflow: workflowDetail
? {
id: workflowDetail.id,
name: workflowDetail.pipelineName || workflowDetail.label,
state: workflowDetail.state,
stateLabel: workflowDetail.state === 1 ? "🟢 启用中" : "⚪ 已停用",
totalTasks: workflowDetail.tasks?.length ?? tree.length,
}
: undefined,
executionTree: tree,
failedExecutions,
conditionDiagnoses,
timeline,
},
runtime.outputOptions
),
@@ -422,16 +525,32 @@ export async function handleJob(parsed: CliParsedArgs, runtime: CliRuntime): Pro
};
}
const treeRows = tree.map((node, idx) => [
idx + 1,
node.id,
node.name || "-",
node.label || node.displayName || "-",
node.type || "-",
node.status || "-",
String((node as Record<string, unknown>).durationTime ?? node.executionTime ?? "-"),
node.error?.message || "-",
]);
const formatJobStatusLabel = (status?: string, state?: unknown): string => {
const s = (status || "").toUpperCase();
if (s === "STARTED" || s === "RUNNING") return "⏳ 运行中 (STARTED)";
if (s === "COMPLETED" || s === "SUCCESS") return "✅ 已完成 (COMPLETED)";
if (s === "FAILED" || s === "ERROR") return "❌ 失败 (FAILED)";
if (s === "STOP" || s === "STOPPED") return "🛑 终止 (STOPPED)";
if (s === "CANCELLED" || s === "CANCELED") return "🚫 已取消";
return s || String(state ?? "-");
};
const treeRows = tree.map((node, idx) => {
const isRunning = node.status === "STARTED" || node.status === "RUNNING";
const statusLabel = isRunning
? (node.type === "task-dynamic-delay" ? "⏳ 延时等待中" : "⏳ 运行中")
: node.status || "-";
return [
idx + 1,
node.id,
node.name || "-",
node.label || node.displayName || "-",
node.type || "-",
statusLabel,
String((node as Record<string, unknown>).durationTime ?? node.executionTime ?? "-"),
node.error?.message || "-",
];
});
const failedRows = failedExecutions.map((item, idx) => [
idx + 1,
@@ -444,18 +563,32 @@ export async function handleJob(parsed: CliParsedArgs, runtime: CliRuntime): Pro
item.error?.message || "-",
]);
const hasUnexecuted = workflowDetail && workflowDetail.tasks && workflowDetail.tasks.length > tree.length;
const isJobRunning = (job.status || "").toUpperCase() === "STARTED" || (job.status || "").toUpperCase() === "RUNNING";
const outLines = [
`====== 工作流 Job 执行详情 [${job.id}] ======`,
printKeyValue({
"Job ID": job.id,
"工作流 ID (pipelineId)": job.pipelineId,
"Job 状态 (state)": job.state ?? job.status,
...(workflowDetail ? { "工作流名称": workflowDetail.pipelineName || workflowDetail.label } : {}),
"工作流状态": workflowDetail?.state === 1 ? "🟢 启用中" : "⚪ 已停用",
"Job 状态 (state)": formatJobStatusLabel(job.status, job.state),
"开始时间": job.startTime || "-",
"结束时间": job.endTime || "-",
"耗时(ms)": String(job.durationTime ?? "-"),
"顶层节点数": tree.length,
"定义总步骤数": workflowDetail?.tasks?.length ?? tree.length,
"已调度节点数": tree.length,
...(hasUnexecuted ? { "未执行步骤数": workflowDetail.tasks.length - tree.length } : {}),
"异常/跳过节点数": failedExecutions.length,
}),
...(hasUnexecuted
? [
"",
isJobRunning
? `💡 提示: 该流程定义共 ${workflowDetail.tasks.length} 步,当前正在执行第 ${tree.length} 步(延时等待中或任务处理中),后续 ${workflowDetail.tasks.length - tree.length} 个步骤尚未调度。运行 'hose-use workflow job ${job.id} --timeline' 可查看实时节点进度。`
: `💡 提示: 该流程定义共 ${workflowDetail.tasks.length} 步,本次调度在第 ${tree.length} 步中断,后续 ${workflowDetail.tasks.length - tree.length} 个步骤未执行。运行 'hose-use workflow job ${job.id} --timeline' 查看全链路步骤时间线。`,
]
: []),
"",
"── 顶层节点执行树 ──",
treeRows.length
+1 -1
View File
@@ -3,7 +3,7 @@ import { stringOption } from "../../parser.js";
import { createClientsForCorp, createPiperClientForCorp } from "../../helpers.js";
import type { CliParsedArgs, CliRuntime } from "../../types.js";
export const PLATFORM_ID_OPTION_KEYS = ["platform-id", "platformId", "app-id", "appId"];
export const PLATFORM_ID_OPTION_KEYS = ["platform", "platform-id", "platformId", "app", "app-id", "appId"];
export async function createWorkflowDetailClient(
parsed: CliParsedArgs,
+32 -2
View File
@@ -88,9 +88,39 @@ export async function handleWorkflowTest(
}
case "WEBHOOK": {
// 分支 B: Webhook / 外部事件触发器 ── 支持 sample / body / file / empty
// 分支 B: Webhook / 外部事件触发器 ── 支持 flow/bill / sample / body / file / empty
targetId = "";
if (rawBody) {
if (flowCodeOrId && !rawBody && !filePath) {
try {
const { getBillByCodeOrId } = await import("../../../domains/bill/tools.js");
const { createSessionClient } = await import("../../../core/http/index.js");
const sessionClient = await createSessionClient(runtime.selectedCorp!);
const corpId = runtime.selectedCorp?.corpId || runtime.selectedCorp?.id || "";
const bills = await getBillByCodeOrId(sessionClient, corpId, flowCodeOrId);
const bill = bills[0];
if (bill) {
customPayload = {
code: bill.billCode,
flowId: bill.billId,
title: bill.title,
data: bill,
corporationId: corpId,
};
} else {
customPayload = {
code: flowCodeOrId,
flowId: flowCodeOrId,
corporationId: corpId,
};
}
} catch {
customPayload = {
code: flowCodeOrId,
flowId: flowCodeOrId,
corporationId: runtime.selectedCorp?.corpId || runtime.selectedCorp?.id,
};
}
} else if (rawBody) {
try {
customPayload = JSON.parse(rawBody);
} catch (e: any) {