From aea30fbcd569b9f624781739ac7a5f1754c26437 Mon Sep 17 00:00:00 2001 From: yunyingk Date: Wed, 21 Oct 2026 17:21:35 +0800 Subject: [PATCH] =?UTF-8?q?feat(workflow):=20=E5=87=86=E7=A1=AE=E8=AF=86?= =?UTF-8?q?=E5=88=AB=E5=B7=A5=E4=BD=9C=E6=B5=81=E5=BB=B6=E6=97=B6=E6=89=A7?= =?UTF-8?q?=E8=A1=8C=E4=B8=8E=E5=9C=A8=E9=80=94=E8=BF=90=E8=A1=8C=E7=8A=B6?= =?UTF-8?q?=E6=80=81=E5=B9=B6=E8=A1=A5=E5=85=A8=E8=8A=82=E7=82=B9=E5=AD=97?= =?UTF-8?q?=E5=85=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/cli/command-metadata.ts | 2 +- src/cli/commands/probe.ts | 30 +++ src/cli/commands/workflow.test.ts | 178 ++++++++++++++++++ src/cli/commands/workflow/history.ts | 95 ++++++++-- src/cli/commands/workflow/job.ts | 159 ++++++++++++++-- src/cli/commands/workflow/shared.ts | 2 +- src/cli/commands/workflow/test.ts | 34 +++- src/core/http/script-engine-client.ts | 48 +++-- src/core/http/unity-client.ts | 67 ++++--- src/domains/platform/api.ts | 11 +- src/domains/platform/types.ts | 41 +++- .../platform/workflow/analysis/analyzer.ts | 1 + .../platform/workflow/nodes/mutations.ts | 15 ++ src/domains/platform/workflow/nodes/tree.ts | 4 + .../platform/workflow/watch/helpers.ts | 6 +- 15 files changed, 615 insertions(+), 78 deletions(-) diff --git a/src/cli/command-metadata.ts b/src/cli/command-metadata.ts index dbf166e..e742bce 100644 --- a/src/cli/command-metadata.ts +++ b/src/cli/command-metadata.ts @@ -272,7 +272,7 @@ export const COMMAND_METADATA: Record = { "dictionary": "enum", "dict": "enum" }, - flags: { ...flagList("all allow-prod allow-production auto-publish autoPublish compare detail diff empty errors f fail fail-on-alert failOnAlert failed failed-only failedOnly follow force force-write forceWrite has-error hasError in-place inPlace includeDetail json none once publish snapshot v value-json valueJson verbose", "boolean"), ...flagList("a admin-key adminKey after app-id appId b bill body c code code-file container count d data desc description end-time endTime entity execution-logs field file filter flow flow-code flowCode from i id input input-file insert-after interval job job-id job1 job2 jobA jobB jobId keyword l label log logs max-jobs maxJobs n name node node-id nodeId nodes output output-file outputFile p page page-size pageSize parent parent-id parentId password path payload pipeline pipeline-id pipelineId platform-id platformId pwd query record s sample sample-id sampleId set size snapshot1 snapshot2 snapshotA snapshotB source start-time startTime state state-file stateFile t target targetName targetPlatformId task taskType third-id thirdId timeout timeout-ms timeoutMs to trigger type types value workflowId", "value") } + flags: { ...flagList("all allow-prod allow-production auto-publish autoPublish compare detail diff empty errors f fail fail-on-alert failOnAlert failed failed-only failedOnly follow force force-write forceWrite has-error hasError in-place inPlace includeDetail json none once publish snapshot v value-json valueJson verbose timeline progress steps", "boolean"), ...flagList("a admin-key adminKey after app app-id appId b bill body c code code-file container count d data desc description end-time endTime entity execution-logs field file filter flow flow-code flowCode from i id input input-file insert-after interval job job-id job1 job2 jobA jobB jobId keyword l label log logs max-jobs maxJobs n name node node-id nodeId nodes output output-file outputFile p page page-size pageSize parent parent-id parentId password path payload pipeline pipeline-id pipelineId platform platform-id platformId pwd query record s sample sample-id sampleId set size snapshot1 snapshot2 snapshotA snapshotB source start-time startTime state state-file stateFile t target targetName targetPlatformId task taskType third-id thirdId timeout timeout-ms timeoutMs to trigger type types value workflowId", "value") } }, "bill": { "summary": "单据检索、表单规格诊断与审批动作", diff --git a/src/cli/commands/probe.ts b/src/cli/commands/probe.ts index 3d66498..d43a8fa 100644 --- a/src/cli/commands/probe.ts +++ b/src/cli/commands/probe.ts @@ -27,6 +27,7 @@ export async function handleProbeCommand( env: currentCorp.env, isTest: currentCorp.isTest, staffId: currentCorp.credentials.staffId, + staffName: currentCorp.staffName || currentCorp.session?.staffName, baseUrl: currentCorp.baseUrl, source: currentCorp.source, accountId: currentCorp.accountId, @@ -52,6 +53,35 @@ export async function handleProbeCommand( loginStaffId: sessionRes.value?.loginStaffId, expTime: sessionRes.value?.expTime ? new Date(sessionRes.value.expTime).toLocaleString() : undefined, }; + + // 自愈补全员工姓名 (Self-Healing Profile Hydration) + if (!currentCorp.staffName && !currentCorp.session?.staffName) { + if (hasOpenApi && currentCorp.credentials.appKey && currentCorp.credentials.appSecurity && currentCorp.credentials.staffId) { + try { + const { fetchHoseOpenApiAccessToken, fetchHoseStaffDetails } = await import("../../core/auth/openapi-v1.js"); + const openapiToken = await fetchHoseOpenApiAccessToken({ + baseUrl: currentCorp.baseUrl, + appKey: currentCorp.credentials.appKey, + appSecurity: currentCorp.credentials.appSecurity, + }); + const details = await fetchHoseStaffDetails(currentCorp.baseUrl || "https://app.ekuaibao.com", openapiToken, [currentCorp.credentials.staffId]); + if (details[0]?.name) { + currentCorp.staffName = details[0].name; + if (!currentCorp.session) { + currentCorp.session = { staffName: details[0].name } as any; + } else { + currentCorp.session.staffName = details[0].name; + } + if (details[0].cellphone && currentCorp.session) { + currentCorp.session.cellphone = details[0].cellphone; + } + (results.enterprise as any).staffName = details[0].name; + const { saveCorpConfig } = await import("../../core/config/loader.js"); + saveCorpConfig(currentCorp); + } + } catch {} + } + } } catch (e) { results.ekbSession = { status: "error", diff --git a/src/cli/commands/workflow.test.ts b/src/cli/commands/workflow.test.ts index 7803f83..30e678d 100644 --- a/src/cli/commands/workflow.test.ts +++ b/src/cli/commands/workflow.test.ts @@ -1989,5 +1989,183 @@ describe("CLI - workflow job 执行详情与异常精准透视", () => { expect(wfEvalRes.stdout).toContain("执行成功 ✅"); expect(wfEvalRes.stdout).toContain('"total": 100'); }); + + it("workflow logs correctly detects and formats running/delayed jobs and in-progress count", async () => { + const mockDetail = { + id: "pipe_delay_test", + pipelineName: "审批延时测试流程", + state: 1, + tasks: [ + { name: "trigger_1", type: "clock", label: "定时触发" }, + { name: "action_delay_1", type: "task-dynamic-delay", label: "延时等待节点", sleepTime: 60 }, + { name: "action_js_1", type: "code-js2", label: "通知节点" }, + ], + }; + + const mockLogs = { + executeCount: 3, + successCount: 2, + errorCount: 0, + number: 1, + size: 10, + totalPages: 1, + totalItems: 3, + jobList: [ + { + state: 0, + jobName: "审批延时测试流程", + jobId: "job_running_001", + executeTime: "2026-10-21 17:15:00", + status: "STARTED", + runType: "DEBUG", + successTaskCount: 1, + errorTaskCount: 0, + hasError: "不存在", + }, + { + state: 0, + jobName: "审批延时测试流程", + jobId: "job_completed_002", + executeTime: "2026-10-21 17:10:00", + status: "COMPLETED", + runType: "DEBUG", + successTaskCount: 3, + errorTaskCount: 0, + hasError: "不存在", + }, + ], + }; + + const mockClient = { + get: (url: string) => ({ + json: async () => { + if (url.includes("/log")) return { code: 200, data: mockLogs }; + return { code: 200, data: mockDetail }; + }, + }), + }; + + 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)); + + // 1. All logs view + const allLogsRes = await handleWorkflowCommand( + { + area: "workflow", + action: "logs", + args: ["pipe_delay_test"], + options: {}, + raw: ["workflow", "logs", "pipe_delay_test"], + }, + mockRuntime + ); + expect(allLogsRes.exitCode).toBe(0); + expect(allLogsRes.stdout).toContain("运行中/延时"); + expect(allLogsRes.stdout).toContain("1 (正在执行或延时等待中)"); + expect(allLogsRes.stdout).toContain("⏳ 运行中"); + expect(allLogsRes.stdout).toContain("✅ 已完成"); + expect(allLogsRes.stdout).toContain("⏳ 执行中"); + + // 2. Client-side filtering by --state=RUNNING + const runningOnlyRes = await handleWorkflowCommand( + { + area: "workflow", + action: "logs", + args: ["pipe_delay_test"], + options: { state: "RUNNING" }, + raw: ["workflow", "logs", "pipe_delay_test", "--state=RUNNING"], + }, + mockRuntime + ); + expect(runningOnlyRes.exitCode).toBe(0); + expect(runningOnlyRes.stdout).toContain("job_running_001"); + expect(runningOnlyRes.stdout).not.toContain("job_completed_002"); + }); + + it("workflow job correctly displays mid-flight delayed job progress and non-interruptive hints", async () => { + const mockDetail = { + id: "pipe_delay_test", + pipelineName: "审批延时测试流程", + state: 1, + tasks: [ + { name: "trigger_1", type: "clock", label: "定时触发" }, + { name: "action_delay_1", type: "task-dynamic-delay", label: "延时等待节点", sleepTime: 60 }, + { name: "action_js_1", type: "code-js2", label: "通知节点" }, + ], + }; + + const mockRunningJob = { + id: "job_running_001", + pipelineId: "pipe_delay_test", + status: "STARTED", + state: 0, + startTime: 1792574000000, + }; + + const mockExecutionTree = [ + { id: "exec_1", name: "trigger_1", label: "定时触发", type: "clock", status: "COMPLETED", durationTime: 10 }, + { id: "exec_2", name: "action_delay_1", label: "延时等待节点", type: "task-dynamic-delay", status: "STARTED" }, + ]; + + const mockClient = { + get: (url: string) => ({ + json: async () => { + if (url.includes("/execution")) return { code: 200, data: mockExecutionTree }; + if (url.includes("/failed")) return { code: 200, data: { items: [] } }; + if (url.includes("/jobs/job_running_001")) return { code: 200, data: mockRunningJob }; + return { code: 200, data: mockDetail }; + }, + }), + }; + + 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)); + + // 1. Overview view + const jobRes = await handleWorkflowCommand( + { + area: "workflow", + action: "job", + args: ["job_running_001"], + options: {}, + raw: ["workflow", "job", "job_running_001"], + }, + mockRuntime + ); + expect(jobRes.exitCode).toBe(0); + expect(jobRes.stdout).toContain("⏳ 运行中 (STARTED)"); + expect(jobRes.stdout).toContain("当前正在执行第 2 步(延时等待中或任务处理中)"); + expect(jobRes.stdout).not.toContain("本次调度在第 2 步中断"); + expect(jobRes.stdout).toContain("⏳ 延时等待中"); + + // 2. Timeline view + const timelineRes = await handleWorkflowCommand( + { + area: "workflow", + action: "job", + args: ["job_running_001"], + options: { timeline: true }, + raw: ["workflow", "job", "job_running_001", "--timeline"], + }, + mockRuntime + ); + expect(timelineRes.exitCode).toBe(0); + expect(timelineRes.stdout).toContain("✅ 已完成"); + expect(timelineRes.stdout).toContain("⏳ 延时等待中"); + expect(timelineRes.stdout).toContain("⏳ 等待前序步骤执行完成"); + expect(timelineRes.stdout).not.toContain("因前序步骤中断"); + }); }); diff --git a/src/cli/commands/workflow/history.ts b/src/cli/commands/workflow/history.ts index 661435d..a51575c 100644 --- a/src/cli/commands/workflow/history.ts +++ b/src/cli/commands/workflow/history.ts @@ -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, }), diff --git a/src/cli/commands/workflow/job.ts b/src/cli/commands/workflow/job.ts index d82dd32..90750b3 100644 --- a/src/cli/commands/workflow/job.ts +++ b/src/cli/commands/workflow/job.ts @@ -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= 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).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).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 diff --git a/src/cli/commands/workflow/shared.ts b/src/cli/commands/workflow/shared.ts index d1127b1..b8dac45 100644 --- a/src/cli/commands/workflow/shared.ts +++ b/src/cli/commands/workflow/shared.ts @@ -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, diff --git a/src/cli/commands/workflow/test.ts b/src/cli/commands/workflow/test.ts index 177fa28..813066c 100644 --- a/src/cli/commands/workflow/test.ts +++ b/src/cli/commands/workflow/test.ts @@ -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) { diff --git a/src/core/http/script-engine-client.ts b/src/core/http/script-engine-client.ts index 6ec04de..8bfd242 100644 --- a/src/core/http/script-engine-client.ts +++ b/src/core/http/script-engine-client.ts @@ -118,11 +118,17 @@ export async function getScriptEngineClient( const cachedHoseToken = mem.hoseToken; return createAuthClient({ prefixUrl: SCRIPT_ENGINE_BASE_URL, - getHeaders: () => ({ - Authorization: `Bearer ${scriptEngineMemoryCache.get(cacheKey)?.jwt ?? cachedJwt}`, - platformid: platformId, - hoseaccesstoken: scriptEngineMemoryCache.get(cacheKey)?.hoseToken ?? cachedHoseToken, - }), + getHeaders: () => { + const headers: Record = { + Authorization: `Bearer ${scriptEngineMemoryCache.get(cacheKey)?.jwt ?? cachedJwt}`, + platformid: platformId, + }; + const currentHoseToken = scriptEngineMemoryCache.get(cacheKey)?.hoseToken ?? cachedHoseToken; + if (currentHoseToken) { + headers.hoseaccesstoken = currentHoseToken; + } + return headers; + }, onUnauthorized: async () => { invalidateScriptEngineCache(corp.id, cacheKey); if (canRefreshCorpAccessToken(corp)) await refreshSingleCorpAccessToken(corp); @@ -144,11 +150,17 @@ export async function getScriptEngineClient( const baseUrl = corp.baseUrl || EKB_BASE_URL; // 重新换取 - const hoseToken = await fetchHoseToken( - corp.credentials.accessToken, - corpId, - environment - ); + let hoseToken = ""; + try { + hoseToken = await fetchHoseToken( + corp.credentials.accessToken, + corpId, + environment + ); + } catch { + // 独立私有化域名或部分仅持 OpenAPI 凭证的租户在 business-center 换取 hose-access-token 可能受限, + // 此处优雅降级避免阻塞 Piper / ScriptEngine 客户端构建 + } const easoJwt = await fetchEasoJwt( corp.credentials.accessToken, corpId, @@ -179,11 +191,17 @@ export async function getScriptEngineClient( return createAuthClient({ prefixUrl: SCRIPT_ENGINE_BASE_URL, - getHeaders: () => ({ - Authorization: `Bearer ${scriptEngineMemoryCache.get(cacheKey)?.jwt ?? easoJwt}`, - platformid: platformId, - hoseaccesstoken: scriptEngineMemoryCache.get(cacheKey)?.hoseToken ?? hoseToken, - }), + getHeaders: () => { + const headers: Record = { + Authorization: `Bearer ${scriptEngineMemoryCache.get(cacheKey)?.jwt ?? easoJwt}`, + platformid: platformId, + }; + const currentHoseToken = scriptEngineMemoryCache.get(cacheKey)?.hoseToken ?? hoseToken; + if (currentHoseToken) { + headers.hoseaccesstoken = currentHoseToken; + } + return headers; + }, onUnauthorized: async () => { invalidateScriptEngineCache(corp.id, cacheKey); if (canRefreshCorpAccessToken(corp)) await refreshSingleCorpAccessToken(corp); diff --git a/src/core/http/unity-client.ts b/src/core/http/unity-client.ts index a102070..4b4ef41 100644 --- a/src/core/http/unity-client.ts +++ b/src/core/http/unity-client.ts @@ -107,15 +107,18 @@ export async function fetchUnityJwt( export async function fetchEasoRealmToken( corpId: string, unityJwt: string, - hoseToken: string + hoseToken?: string ): Promise { + const headers: Record = { + Authorization: `Bearer ${unityJwt}`, + }; + if (hoseToken) { + headers.hoseaccesstoken = hoseToken; + } const response = await ky .get(`${EASO_BASE_URL}/api/realms/EASO`, { searchParams: { corpId }, - headers: { - Authorization: `Bearer ${unityJwt}`, - hoseaccesstoken: hoseToken, - }, + headers, }) .json<{ value?: { accessToken?: string } }>(); const token = response.value?.accessToken; @@ -185,12 +188,18 @@ export async function getEasoClient(corp: CorpConfig): Promise<{ return { client: createAuthClient({ prefixUrl: EASO_BASE_URL, - getHeaders: () => ({ - Authorization: `Bearer ${easoMemoryCache.get(cacheKey)?.token ?? cachedToken}`, - accesstoken: corp.credentials.accessToken, - corporationid: corpId, - hoseaccesstoken: easoMemoryCache.get(cacheKey)?.hoseToken ?? cachedHoseToken, - }), + getHeaders: () => { + const headers: Record = { + Authorization: `Bearer ${easoMemoryCache.get(cacheKey)?.token ?? cachedToken}`, + accesstoken: corp.credentials.accessToken, + corporationid: corpId, + }; + const currentHoseToken = easoMemoryCache.get(cacheKey)?.hoseToken ?? cachedHoseToken; + if (currentHoseToken) { + headers.hoseaccesstoken = currentHoseToken; + } + return headers; + }, onUnauthorized: async () => { invalidateEasoCache(corp.id); if (canRefreshCorpAccessToken(corp)) await refreshSingleCorpAccessToken(corp); @@ -212,11 +221,17 @@ export async function getEasoClient(corp: CorpConfig): Promise<{ const baseUrl = corp.baseUrl || EKB_BASE_URL; // 重新换取 - const hoseToken = await fetchHoseToken( - corp.credentials.accessToken, - corpId, - environment - ); + let hoseToken = ""; + try { + hoseToken = await fetchHoseToken( + corp.credentials.accessToken, + corpId, + environment + ); + } catch { + // 独立私有化域名或部分仅持 OpenAPI 凭证的租户在 business-center 换取 hose-access-token 可能受限, + // 但 EASO Realm 换票仅依赖 Unity JWT 即可完成鉴权,此处降级兼容以避免阻断 + } const unityJwt = await fetchUnityJwt( corp.credentials.accessToken, corpId, @@ -226,7 +241,7 @@ export async function getEasoClient(corp: CorpConfig): Promise<{ const easoToken = await fetchEasoRealmToken( corpId, unityJwt, - hoseToken + hoseToken || undefined ); const expiresAt = Date.now() + 2 * 60 * 60 * 1000; // 2小时 @@ -265,12 +280,18 @@ export async function getEasoClient(corp: CorpConfig): Promise<{ return { client: createAuthClient({ prefixUrl: EASO_BASE_URL, - getHeaders: () => ({ - Authorization: `Bearer ${easoMemoryCache.get(cacheKey)?.token ?? easoToken}`, - accesstoken: corp.credentials.accessToken, - corporationid: corpId, - hoseaccesstoken: easoMemoryCache.get(cacheKey)?.hoseToken ?? hoseToken, - }), + getHeaders: () => { + const headers: Record = { + Authorization: `Bearer ${easoMemoryCache.get(cacheKey)?.token ?? easoToken}`, + accesstoken: corp.credentials.accessToken, + corporationid: corpId, + }; + const currentHoseToken = easoMemoryCache.get(cacheKey)?.hoseToken ?? hoseToken; + if (currentHoseToken) { + headers.hoseaccesstoken = currentHoseToken; + } + return headers; + }, onUnauthorized: async () => { invalidateEasoCache(corp.id); if (canRefreshCorpAccessToken(corp)) await refreshSingleCorpAccessToken(corp); diff --git a/src/domains/platform/api.ts b/src/domains/platform/api.ts index c977ad0..5d5f7a0 100644 --- a/src/domains/platform/api.ts +++ b/src/domains/platform/api.ts @@ -240,7 +240,16 @@ export async function listRunningJobs( const response = await client.get("api/easo/jobs/running", { searchParams: { pipelineId, runType }, }); - return unwrap(response, z.array(WorkflowJobSchema)); + const json = (await response.json()) as { code?: number; data?: unknown }; + const rawData = json?.data; + if (!rawData) return []; + if (Array.isArray(rawData)) { + return z.array(WorkflowJobSchema).parse(rawData); + } + if (typeof rawData === "object") { + return [WorkflowJobSchema.parse(rawData)]; + } + return []; } export async function getJob( diff --git a/src/domains/platform/types.ts b/src/domains/platform/types.ts index 0aa89e4..3a01140 100644 --- a/src/domains/platform/types.ts +++ b/src/domains/platform/types.ts @@ -188,6 +188,11 @@ export const FlowCreateTaskSchema = BaseTaskSchema.extend({ onError: OnErrorSchema.optional(), }); +export const DynamicDelayTaskSchema = BaseTaskSchema.extend({ + type: z.literal("task-dynamic-delay"), + sleepTime: z.union([z.number(), z.string()]).optional(), +}); + // 兜底节点:遇到未收录类型时仍保留全部字段 export const UnknownTaskSchema = z .object({ @@ -217,6 +222,7 @@ export const WorkflowTaskSchema: z.ZodType = z.union([ EkuaibaoDatalinkCreateTaskSchema, DataConvertTaskSchema, FlowCreateTaskSchema, + DynamicDelayTaskSchema, UnknownTaskSchema, ]); @@ -351,14 +357,33 @@ export const WorkflowChargeSchema = z.object({ // ── 运行中的任务与单次 Job 执行详情 ────────────────────────────────────────── -export const WorkflowJobSchema = z.object({ - id: z.string(), - pipelineId: z.string(), - status: z.string().default(""), - startTime: z.union([z.string(), z.number()]).optional(), - endTime: z.union([z.string(), z.number()]).optional(), - triggerType: z.string().default(""), -}); +export const WorkflowJobSchema = z + .object({ + id: z.string().optional(), + jobId: z.string().optional(), + pipelineId: z.string().nullish().default(""), + jobName: z.string().nullish(), + status: z.string().default(""), + runType: z.string().default(""), + executeTime: z.union([z.string(), z.number()]).nullish(), + startTime: z.union([z.string(), z.number()]).nullish(), + endTime: z.union([z.string(), z.number()]).nullish(), + triggerType: z.string().default(""), + successTaskCount: z.number().nullish().default(0), + errorTaskCount: z.number().nullish().default(0), + hasError: z.union([z.string(), z.boolean()]).nullish(), + state: z.union([z.number(), z.string()]).nullish(), + autoPublish: z.boolean().nullish(), + version: z.string().nullish(), + snapshotId: z.string().nullish(), + }) + .passthrough() + .transform((val) => ({ + ...val, + id: val.id || val.jobId || "", + jobId: val.jobId || val.id || "", + pipelineId: val.pipelineId || "", + })); export const WorkflowJobDetailSchema = z .object({ diff --git a/src/domains/platform/workflow/analysis/analyzer.ts b/src/domains/platform/workflow/analysis/analyzer.ts index f6d76d2..8c1e40d 100644 --- a/src/domains/platform/workflow/analysis/analyzer.ts +++ b/src/domains/platform/workflow/analysis/analyzer.ts @@ -50,6 +50,7 @@ const KNOWN_TYPES = new Set([ "ekuaibao-datalink-delete-trigger", "data-convert", "flow-create-task", + "task-dynamic-delay", ]); function referencesFromTask(task: WorkflowTask): string[] { diff --git a/src/domains/platform/workflow/nodes/mutations.ts b/src/domains/platform/workflow/nodes/mutations.ts index af278b7..c04fe14 100644 --- a/src/domains/platform/workflow/nodes/mutations.ts +++ b/src/domains/platform/workflow/nodes/mutations.ts @@ -175,6 +175,21 @@ export function buildWorkflowTask(type: string, options: Partial ...options.extra, }; + case "task-dynamic-delay": + case "delay": + return { + name, + type: "task-dynamic-delay", + label: options.label || "延迟执行节点", + desc: options.desc || "在工作流中暂停等待指定秒数", + groupName: "action", + orderIndex: 0, + levelIndex: [0], + status: "active", + sleepTime: options.extra?.sleepTime ?? 60, + ...options.extra, + }; + default: return { name, diff --git a/src/domains/platform/workflow/nodes/tree.ts b/src/domains/platform/workflow/nodes/tree.ts index 705972b..9e14472 100644 --- a/src/domains/platform/workflow/nodes/tree.ts +++ b/src/domains/platform/workflow/nodes/tree.ts @@ -30,6 +30,10 @@ export function summarizeTask(task: WorkflowTask): string { if (task.type === "stop") { return "阻断终止流程"; } + if (task.type === "task-dynamic-delay") { + const sleep = (task as any).sleepTime; + return sleep !== undefined && sleep !== null ? `延迟等待: ${sleep} 秒` : "延迟等待节点"; + } if (task.type === "ekuaibao-datalink-create-trigger") { return "业务对象台账新增触发"; } diff --git a/src/domains/platform/workflow/watch/helpers.ts b/src/domains/platform/workflow/watch/helpers.ts index a8f777a..881da1b 100644 --- a/src/domains/platform/workflow/watch/helpers.ts +++ b/src/domains/platform/workflow/watch/helpers.ts @@ -7,11 +7,13 @@ export function normalizeJobStatus(job?: Partial | Record