feat(workflow): implement real-time workflow tail and watch commands

This commit is contained in:
gitea committed 2026-10-15 16:37:27 +08:00
1 parent 71f9879f68
commit 53201ba4e1
11 files changed
+1310 -7

No files matched your search

+2
View File
@@ -10,6 +10,7 @@ src/domains/platform/
├── api.ts # HTTP 传输层(含 unwrap 空安全校验与 Piper Job 5 大诊断端点)
├── analysis.ts # 工作流静态分析(禁用状态、SKIP 无状态守卫、单据联动覆盖诊断)
├── workflow-nodes.ts # 节点树展平、树形索引定位、声明式增删改与索引重排 SDK
├── workflow-watch.ts # 实时任务监听、增量状态跃迁追踪与执行日志流引擎
└── tools.ts # MCP tool 注册 + 服务层聚合函数
```
@@ -33,6 +34,7 @@ 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]
```
## 触发器分类与调测路径分支 (Path Branching)
+1 -3
View File
@@ -941,6 +941,4 @@ export async function getWorkflowSampleData(
}
export * from "./workflow-nodes.js";
export * from "./workflow-watch.js";
+374
View File
@@ -0,0 +1,374 @@
import { describe, expect, it } from "bun:test";
import {
TaskExecutionTracker,
formatWatchEvent,
normalizeJobStatus,
isJobTerminal,
extractTaskErrorMessage,
watchSingleJob,
watchWorkflowPipeline,
type WorkflowWatchEvent,
} from "./workflow-watch.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);
});
});
});
+645
View File
@@ -0,0 +1,645 @@
import type { KyInstance } from "ky";
import type { WorkflowJobDetail, WorkflowTaskExecution } from "./types.js";
import * as api from "./api.js";
import { flattenExecutionTree, isTaskExecutionFailed } from "./services.js";
export type WorkflowWatchEventType =
| "pipeline_watch_start"
| "job_detected"
| "task_started"
| "task_completed"
| "task_failed"
| "task_skipped"
| "job_completed"
| "idle"
| "timeout";
export interface WorkflowWatchEvent {
type: WorkflowWatchEventType;
pipelineId?: string;
pipelineLabel?: string;
jobId?: string;
runType?: string;
executionId?: string;
name?: string;
displayName?: string;
label?: string;
taskType?: string;
status?: string;
durationMs?: number;
startTime?: string;
loopPath?: string;
error?: string;
jobSummary?: {
status: string;
durationMs?: number;
successCount: number;
errorCount: number;
hasError: boolean;
};
timestamp: number;
}
export interface WatchWorkflowOptions {
jobId?: string;
intervalMs?: number;
timeoutMs?: number;
maxJobs?: number;
once?: boolean;
follow?: boolean;
failedOnly?: boolean;
onEvent?: (event: WorkflowWatchEvent) => Promise<void> | void;
signal?: AbortSignal;
}
export interface WatchedJobResult {
jobId: string;
pipelineId: string;
status: string;
runType?: string;
durationMs?: number;
successCount: number;
errorCount: number;
hasError: boolean;
events: WorkflowWatchEvent[];
}
export interface WorkflowWatchReport {
pipelineId: string;
totalJobsWatched: number;
jobs: WatchedJobResult[];
timedOut: boolean;
hasFailures: boolean;
}
const TERMINAL_STATES = new Set(["COMPLETED", "FAILED", "STOP", "STOPPED", "CANCELLED", "CANCELED"]);
export function normalizeJobStatus(job?: Partial<WorkflowJobDetail> | Record<string, unknown> | null): string {
if (!job) return "UNKNOWN";
const rawStatus = (job as any).status;
const rawState = (job as any).state;
if (typeof rawStatus === "string" && rawStatus.trim()) {
return rawStatus.trim().toUpperCase();
}
if (rawState === 0 || rawState === "0") return "COMPLETED";
if (rawState === 1 || rawState === "1") return "RUNNING";
if (rawState === 2 || rawState === "2") return "FAILED";
if (rawState !== undefined && rawState !== null) return String(rawState).toUpperCase();
return "UNKNOWN";
}
export function isJobTerminal(status: string): boolean {
return TERMINAL_STATES.has(status.toUpperCase());
}
/**
* 提取节点执行失败或跳过时的具体错误原因
*/
export function extractTaskErrorMessage(node: WorkflowTaskExecution): string | undefined {
if (!node) return undefined;
const anyNode = node as any;
if (node.error?.message && String(node.error.message).trim()) {
return String(node.error.message).trim();
}
if (anyNode.errorMessage && String(anyNode.errorMessage).trim()) {
return String(anyNode.errorMessage).trim();
}
const outputs = anyNode.outputs ?? anyNode.output;
if (outputs && typeof outputs === "object") {
if (outputs.error) {
return typeof outputs.error === "string" ? outputs.error.trim() : JSON.stringify(outputs.error);
}
if (outputs.message && typeof outputs.message === "string") {
return outputs.message.trim();
}
}
return undefined;
}
/**
* 节点状态追踪器:比对并生成增量任务状态变更事件,避免轮询时重复日志刷屏
*/
export class TaskExecutionTracker {
private seenStatuses = new Map<string, string>();
constructor(public readonly jobId: string) {}
public processExecutions(executions: WorkflowTaskExecution[]): WorkflowWatchEvent[] {
const flattened = flattenExecutionTree(executions);
const events: WorkflowWatchEvent[] = [];
const now = Date.now();
for (const node of flattened) {
if (!node?.id) continue;
const executionId = node.id;
const rawStatus = (node.status || "UNKNOWN").toUpperCase();
const previousStatus = this.seenStatuses.get(executionId);
const name = node.name || executionId;
const label = node.label || node.displayName || undefined;
const displayName = node.displayName || undefined;
const taskType = node.type || "unknown";
const durationMs = typeof node.executionTime === "number" ? node.executionTime : undefined;
const loopPath = node.currentLoopPath || undefined;
const error = extractTaskErrorMessage(node);
const isFailed = isTaskExecutionFailed(node) || rawStatus === "FAILED";
const isSkipped = rawStatus === "SKIPPED" || rawStatus === "SKIP";
if (previousStatus === undefined) {
// 第一次发现该节点
this.seenStatuses.set(executionId, rawStatus);
if (isSkipped) {
events.push({
type: "task_skipped",
jobId: this.jobId,
executionId,
name,
label,
displayName,
taskType,
status: rawStatus,
durationMs,
loopPath,
error,
timestamp: now,
});
} else if (isFailed) {
events.push({
type: "task_failed",
jobId: this.jobId,
executionId,
name,
label,
displayName,
taskType,
status: rawStatus,
durationMs,
loopPath,
error: error || "执行异常或未通过规则校验",
timestamp: now,
});
} else if (rawStatus === "COMPLETED" || rawStatus === "SUCCESS") {
events.push({
type: "task_completed",
jobId: this.jobId,
executionId,
name,
label,
displayName,
taskType,
status: rawStatus,
durationMs,
loopPath,
timestamp: now,
});
} else {
events.push({
type: "task_started",
jobId: this.jobId,
executionId,
name,
label,
displayName,
taskType,
status: rawStatus,
loopPath,
timestamp: now,
});
}
} else if (previousStatus !== rawStatus) {
// 状态发生跃迁(例如从 RUNNING -> COMPLETED 或 FAILED)
this.seenStatuses.set(executionId, rawStatus);
if (isSkipped) {
events.push({
type: "task_skipped",
jobId: this.jobId,
executionId,
name,
label,
displayName,
taskType,
status: rawStatus,
durationMs,
loopPath,
error,
timestamp: now,
});
} else if (isFailed) {
events.push({
type: "task_failed",
jobId: this.jobId,
executionId,
name,
label,
displayName,
taskType,
status: rawStatus,
durationMs,
loopPath,
error: error || "执行异常或未通过规则校验",
timestamp: now,
});
} else if (rawStatus === "COMPLETED" || rawStatus === "SUCCESS") {
events.push({
type: "task_completed",
jobId: this.jobId,
executionId,
name,
label,
displayName,
taskType,
status: rawStatus,
durationMs,
loopPath,
timestamp: now,
});
}
}
}
return events;
}
}
/**
* 将事件格式化为带时间戳的清晰控制台文本行
*/
export function formatWatchEvent(event: WorkflowWatchEvent): string {
const timeStr = new Date(event.timestamp).toTimeString().slice(0, 8);
const tag = `[${timeStr}]`;
switch (event.type) {
case "pipeline_watch_start":
return `${tag} 🔍 开始监听工作流 [${event.pipelineLabel || event.pipelineId}] 运行动态 (按 Ctrl+C 退出)...`;
case "job_detected":
return `${tag} 🚀 捕获新运行任务 Job [${event.jobId}] (${event.runType || "RUN"}, 状态: ${event.status || "RUNNING"})`;
case "task_started":
return ` ⏳ [${event.taskType}] ${event.name || event.executionId}${event.label ? ` (${event.label})` : ""} 开始运行...${event.loopPath ? ` [循环: ${event.loopPath}]` : ""}`;
case "task_completed":
return ` ✓ [${event.taskType}] ${event.name || event.executionId}${event.label ? ` (${event.label})` : ""} COMPLETED (${event.durationMs ?? 0}ms)${event.loopPath ? ` [循环: ${event.loopPath}]` : ""}`;
case "task_skipped": {
const errHint = event.error ? `\n ↳ ⚠️ 异常跳过原因: ${event.error}` : "";
return ` ⚠️ [${event.taskType}] ${event.name || event.executionId}${event.label ? ` (${event.label})` : ""} SKIPPED (${event.durationMs ?? 0}ms)${event.loopPath ? ` [循环: ${event.loopPath}]` : ""}${errHint}`;
}
case "task_failed":
return ` ❌ [${event.taskType}] ${event.name || event.executionId}${event.label ? ` (${event.label})` : ""} FAILED (${event.durationMs ?? 0}ms)${event.loopPath ? ` [循环: ${event.loopPath}]` : ""}\n ↳ 错误详情: ${event.error || "未捕获明确错误信息"}`;
case "job_completed": {
const summary = event.jobSummary;
const isOk = summary?.status === "COMPLETED" && !summary.hasError && summary.errorCount === 0;
const icon = isOk ? "🏁" : "❌";
const statusText = summary?.status || "COMPLETED";
return `${tag} ${icon} Job [${event.jobId}] 执行结束: 状态 [${statusText}] | 耗时: ${summary?.durationMs ?? "-"}ms | 成功: ${summary?.successCount ?? 0} | 失败: ${summary?.errorCount ?? 0} | 存在错误: ${summary?.hasError ? "是" : "否"}`;
}
case "timeout":
return `${tag} ⏱️ 监听超时,未在指定时间内捕获到新的任务状态变更。`;
case "idle":
return `${tag} 💤 暂无新运行实例,继续等待中...`;
default:
return `${tag} [${event.type}]`;
}
}
/**
* 监听指定单个 Job 的实时执行,直至其达到终态或超时
*/
export async function watchSingleJob(
client: KyInstance,
jobId: string,
options: WatchWorkflowOptions = {}
): Promise<WatchedJobResult> {
const intervalMs = Math.max(options.intervalMs ?? 1500, 500);
const timeoutMs = options.timeoutMs ?? 60000;
const startTime = Date.now();
const tracker = new TaskExecutionTracker(jobId);
const events: WorkflowWatchEvent[] = [];
const emit = async (event: WorkflowWatchEvent) => {
if (options.failedOnly) {
if (
event.type !== "task_failed" &&
!(event.type === "task_skipped" && event.error) &&
event.type !== "job_completed" &&
event.type !== "timeout"
) {
return;
}
}
events.push(event);
if (options.onEvent) {
await options.onEvent(event);
}
};
let latestJob: WorkflowJobDetail | undefined;
let isTerminal = false;
while (Date.now() - startTime < timeoutMs) {
if (options.signal?.aborted) break;
try {
latestJob = await api.getJob(client, jobId);
} catch {
// 任务初创可能存在 404/延迟,忽略单次瞬态
}
const currentStatus = normalizeJobStatus(latestJob);
// 获取当前执行树并比对增量事件
try {
const tree = await api.getJobExecutionTree(client, jobId);
const deltaEvents = tracker.processExecutions(tree);
for (const ev of deltaEvents) {
await emit(ev);
}
} catch {
// 忽略执行树瞬态读取异常
}
if (isJobTerminal(currentStatus)) {
isTerminal = true;
break;
}
if (options.once) {
break;
}
const elapsed = Date.now() - startTime;
const remaining = timeoutMs - elapsed;
if (remaining <= 0) break;
await new Promise((resolve) => setTimeout(resolve, Math.min(intervalMs, remaining)));
}
// 终态最后同步一次失败节点信息
let failureItems: WorkflowTaskExecution[] = [];
try {
const failedPage = await api.getJobFailedExecutions(client, jobId);
failureItems = failedPage.items || [];
} catch {
// 忽略
}
const finalStatus = normalizeJobStatus(latestJob);
const anyJob = latestJob as any;
const successCount = Number(anyJob?.successTaskCount ?? 0);
const errorCount = Math.max(Number(anyJob?.errorTaskCount ?? 0), failureItems.length);
const hasError = anyJob?.hasError === true || anyJob?.hasError === "存在" || errorCount > 0 || finalStatus === "FAILED";
const durationMs = typeof anyJob?.durationTime === "number" ? anyJob.durationTime : undefined;
const completionEvent: WorkflowWatchEvent = {
type: "job_completed",
jobId,
status: finalStatus,
timestamp: Date.now(),
jobSummary: {
status: finalStatus,
durationMs,
successCount,
errorCount,
hasError,
},
};
await emit(completionEvent);
return {
jobId,
pipelineId: latestJob?.pipelineId || "",
status: finalStatus,
runType: latestJob?.runType,
durationMs,
successCount,
errorCount,
hasError,
events,
};
}
/**
* 监听工作流流水线:持续捕获新派发的 Job,并实时输出其节点执行动态
*/
export async function watchWorkflowPipeline(
client: KyInstance,
pipelineId: string,
options: WatchWorkflowOptions = {}
): Promise<WorkflowWatchReport> {
const intervalMs = Math.max(options.intervalMs ?? 2000, 500);
const timeoutMs = options.timeoutMs ?? (options.once || options.jobId ? 60000 : Infinity);
const maxJobs = options.jobId ? 1 : (options.maxJobs ?? (options.follow ? Infinity : 1));
const startTime = Date.now();
const watchedJobs: WatchedJobResult[] = [];
const seenJobIds = new Set<string>();
const emit = async (event: WorkflowWatchEvent) => {
if (options.failedOnly) {
if (
event.type !== "task_failed" &&
!(event.type === "task_skipped" && event.error) &&
event.type !== "job_completed" &&
event.type !== "timeout"
) {
return;
}
}
if (options.onEvent) {
await options.onEvent(event);
}
};
// 1. 如果用户显式指定了 --job=<jobId>
if (options.jobId) {
const jobResult = await watchSingleJob(client, options.jobId, {
...options,
onEvent: emit,
});
watchedJobs.push(jobResult);
return {
pipelineId,
totalJobsWatched: 1,
jobs: watchedJobs,
timedOut: false,
hasFailures: jobResult.hasError || jobResult.status === "FAILED",
};
}
// 2. 发出监听开始事件
let pipelineLabel = "";
try {
const detail = await api.getWorkflowDetail(client, pipelineId);
pipelineLabel = detail.label || "";
} catch {
// 忽略标签读取失败
}
await emit({
type: "pipeline_watch_start",
pipelineId,
pipelineLabel,
timestamp: Date.now(),
});
// 如果是一次性快照检视 (--once)
if (options.once) {
let targetJobId: string | undefined;
// 先查是否有正在运行的任务
try {
const running = await api.listRunningJobs(client, pipelineId, "DEBUG");
if (running.length > 0) targetJobId = running[0].id;
} catch {
// 忽略
}
if (!targetJobId) {
try {
const logs = await api.listWorkflowLogs(client, pipelineId, { pageSize: 1 });
if (logs.jobList && logs.jobList.length > 0) {
const first = logs.jobList[0];
targetJobId = first.jobId || first.id;
}
} catch {
// 忽略
}
}
if (!targetJobId) {
return {
pipelineId,
totalJobsWatched: 0,
jobs: [],
timedOut: false,
hasFailures: false,
};
}
const singleRes = await watchSingleJob(client, targetJobId, {
...options,
once: true,
onEvent: emit,
});
return {
pipelineId,
totalJobsWatched: 1,
jobs: [singleRes],
timedOut: false,
hasFailures: singleRes.hasError || singleRes.status === "FAILED",
};
}
// 3. 持续监听循环
let timedOut = false;
// 记录初次启动时的最新已知 JobId,避免将老历史任务当作新触发任务(除非有处于 RUNNING 状态的任务)
try {
const logs = await api.listWorkflowLogs(client, pipelineId, { pageSize: 5 });
for (const j of logs.jobList || []) {
const jid = j.jobId || j.id;
const status = normalizeJobStatus(j);
// 如果不是运行中,标为已知历史
if (jid && !isJobTerminal(status)) {
// 运行中的保留待观察
} else if (jid) {
seenJobIds.add(jid);
}
}
} catch {
// 忽略
}
while (Date.now() - startTime < timeoutMs) {
if (options.signal?.aborted) break;
let candidateJob: { id: string; status: string; runType?: string } | undefined;
// 优先检查 running 接口
try {
const runningJobs = await api.listRunningJobs(client, pipelineId, "DEBUG");
const found = runningJobs.find((j) => !seenJobIds.has(j.id));
if (found) {
candidateJob = { id: found.id, status: found.status || "RUNNING", runType: "DEBUG" };
}
} catch {
// 忽略
}
// 其次检查流水线最新 log
if (!candidateJob) {
try {
const logs = await api.listWorkflowLogs(client, pipelineId, { pageSize: 3 });
for (const j of logs.jobList || []) {
const jid = j.jobId || j.id;
if (jid && !seenJobIds.has(jid)) {
candidateJob = { id: jid, status: normalizeJobStatus(j), runType: j.runType };
break;
}
}
} catch {
// 忽略
}
}
if (candidateJob) {
seenJobIds.add(candidateJob.id);
await emit({
type: "job_detected",
pipelineId,
jobId: candidateJob.id,
status: candidateJob.status,
runType: candidateJob.runType,
timestamp: Date.now(),
});
// 实时跟踪该 Job 执行
const jobResult = await watchSingleJob(client, candidateJob.id, {
...options,
onEvent: emit,
});
watchedJobs.push(jobResult);
if (watchedJobs.length >= maxJobs) {
break;
}
}
const elapsed = Date.now() - startTime;
const remaining = timeoutMs - elapsed;
if (remaining <= 0) {
timedOut = true;
break;
}
await new Promise((resolve) => setTimeout(resolve, Math.min(intervalMs, remaining)));
}
if (Date.now() - startTime >= timeoutMs && watchedJobs.length === 0) {
timedOut = true;
await emit({
type: "timeout",
pipelineId,
timestamp: Date.now(),
});
}
const hasFailures = watchedJobs.some((j) => j.hasError || j.status === "FAILED");
return {
pipelineId,
totalJobsWatched: watchedJobs.length,
jobs: watchedJobs,
timedOut,
hasFailures,
};
}