feat(workflow,corps): add dynamic staff link switching and deep failed job inspection

This commit is contained in:
gitea committed 2026-10-14 18:32:14 +08:00
1 parent 0499ccb2cc
commit 0c6a3ee660
8 files changed
+737 -32

No files matched your search

+46
View File
@@ -344,6 +344,52 @@ describe("cli/commands/corps > handleCorpsCommand search & aliases", () => {
}
});
it("supports dynamic staff switching via corps link [corp] --staff=<id>", async () => {
const originalFetch = globalThis.fetch;
globalThis.fetch = (async () =>
new Response(JSON.stringify({ items: [] }), {
status: 200,
headers: { "content-type": "application/json" },
})) as unknown as typeof fetch;
try {
const res = await handleCorpsCommand(
{
area: "corps",
action: "link",
args: ["corpAlpha"],
options: { staff: "alphaPhysicalId:NEW_ADMIN_STAFF" },
raw: ["corps", "link", "corpAlpha", "--staff=alphaPhysicalId:NEW_ADMIN_STAFF"],
},
searchRuntime
);
expect(res.exitCode).toBe(0);
expect(res.preserveSensitiveStdout).toBe(true);
expect(res.stdout).toContain("NEW_ADMIN_STAFF");
expect(res.stdout).toContain("动态换签");
// --json 模式验证
const jsonRuntime = { ...searchRuntime, jsonMode: true };
const jsonRes = await handleCorpsCommand(
{
area: "corps",
action: "link",
args: ["corpAlpha"],
options: { staff: "alphaPhysicalId:NEW_ADMIN_STAFF", json: true },
raw: ["corps", "link", "corpAlpha", "--staff=alphaPhysicalId:NEW_ADMIN_STAFF", "--json"],
},
jsonRuntime
);
expect(jsonRes.exitCode).toBe(0);
const parsed = JSON.parse(jsonRes.stdout);
expect(parsed.dynamicStaff).toBe(true);
expect(parsed.staffId).toBe("alphaPhysicalId:NEW_ADMIN_STAFF");
} finally {
globalThis.fetch = originalFetch;
}
});
it("supports corps add-persistent --dry-run", async () => {
const res = await handleCorpsCommand(
{
+4
View File
@@ -92,6 +92,8 @@ export function printCorpsHelp(): string {
switch <企业ID> 切换当前激活的工作企业 (别名: use)
current 查看当前激活的企业配置与凭证详情
link [企业ID|名称] 生成企业合思 Web 免密登录直达链接 (别名: hose-link)
[--staff=<姓名|手机号|ID>] 动态指定换签身份
[--persist] 将新身份持久化为企业默认操作人
add-link <URL> 从第三方协助/免密链接导入企业凭证(默认自动探测并持久化 OpenAPI 密钥)
add-persistent 通过 OpenAPI 密钥 (appKey + appSecurity) 持久化接入企业 (别名: add-hose-persistent)
extract-keys <URL> 从协助链接提取企业 OpenAPI 密钥(附加 --save 可直接持久化保存)
@@ -108,6 +110,8 @@ export function printCorpsHelp(): string {
hose-use corps search 17718556446
hose-use corps switch ID01MCcOgJl1td
hose-use corps link 新转转集团
hose-use corps link 新转转集团 --staff="合思-姜尧"
hose-use corps link 新转转集团 --staff="17865187018" --persist
hose-use corps add-link "<url>" --elevate --yes
hose-use corps add-persistent --app-key=... --app-security=... --yes
`.trim();
+117 -2
View File
@@ -1,6 +1,21 @@
import { existsSync } from "node:fs";
import { join } from "node:path";
import { getCorpProvisionalAuthLink, hasOpenApiPersistentCredentials, importFromLink } from "../../../core/auth/login.js";
import {
getCorpProvisionalAuthLink,
hasOpenApiPersistentCredentials,
importFromLink,
} from "../../../core/auth/login.js";
import {
DEFAULT_EKB_BASE_URL,
fetchHoseOpenApiAccessToken,
fetchHoseStaffDetails,
getCorpOpenApiCredentials,
listHoseStaffsByOpenApi,
normalizeBaseUrl,
} from "../../../core/auth/openapi-v1.js";
import { searchStaffs } from "../../../domains/contact/tools.js";
import { NotFoundError, ValidationError } from "../../../core/errors.js";
import type { CorpConfig } from "../../../core/config/types.js";
import { resolveWritableEnterprisesDir } from "../../../core/config/loader.js";
import { stringOption, booleanOption } from "../../parser.js";
import { prompt } from "../../helpers.js";
@@ -9,6 +24,90 @@ import { isDryRun, mutationPreview, requireMutationConfirmation } from "../../mu
import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js";
import { resolveTargetCorpByArgOrContext } from "./shared.js";
export async function resolveStaffForLink(
corp: CorpConfig,
staffQuery: string
): Promise<{ staffId: string; staffName?: string }> {
const q = staffQuery.trim();
if (!q) {
throw new ValidationError("员工检索条件不能为空");
}
const corpId = corp.corpId || corp.credentials.corpId;
// 1. 如果输入本身就是完整 staffId 或 ID01 开头的工号
if (q.includes(":") || (q.startsWith("ID01") && !q.includes(" "))) {
const fullId = q.includes(":") ? q : `${corpId}:${q}`;
const openApiCreds = getCorpOpenApiCredentials(corp);
if (openApiCreds) {
try {
const baseUrl = normalizeBaseUrl(corp.baseUrl || DEFAULT_EKB_BASE_URL);
const openapiToken = await fetchHoseOpenApiAccessToken({
appKey: openApiCreds.appKey,
appSecurity: openApiCreds.appSecurity,
baseUrl,
});
const details = await fetchHoseStaffDetails(baseUrl, openapiToken, [fullId]);
if (details.length > 0 && details[0]?.name) {
return { staffId: fullId, staffName: details[0].name };
}
} catch {
// fallback to using fullId
}
}
return { staffId: fullId };
}
// 2. 若企业已配置 OpenAPI 密钥,优先在管理员(admin 角色)中查找
const openApiCreds = getCorpOpenApiCredentials(corp);
if (openApiCreds) {
try {
const baseUrl = normalizeBaseUrl(corp.baseUrl || DEFAULT_EKB_BASE_URL);
const staffRes = await listHoseStaffsByOpenApi({
appKey: openApiCreds.appKey,
appSecurity: openApiCreds.appSecurity,
domain: baseUrl,
role: "admin",
});
// 优先级 1: 姓名或手机号精确匹配
const exactMatch = staffRes.staffs.find(
(s) => s.name?.trim() === q || s.cellphone?.trim() === q || s.id === q
);
if (exactMatch) {
return { staffId: exactMatch.id, staffName: exactMatch.name };
}
// 优先级 2: 姓名包含模糊匹配
const fuzzyMatch = staffRes.staffs.find((s) => s.name && s.name.includes(q));
if (fuzzyMatch) {
return { staffId: fuzzyMatch.id, staffName: fuzzyMatch.name };
}
} catch {
// 容错并回退至通讯录查询
}
}
// 3. 通道 3: 通讯录常规检索
try {
const matchedStaffs = await searchStaffs(corp, { keyword: q, limit: 10 });
if (matchedStaffs.length > 0) {
const exact = matchedStaffs.find(
(s) => s.name?.trim() === q || s.cellphone?.trim() === q || s.id === q
);
const chosen = exact || matchedStaffs[0];
const normalizedId = chosen.id.includes(":") ? chosen.id : `${corpId}:${chosen.id}`;
return { staffId: normalizedId, staffName: chosen.name };
}
} catch {
// 忽略通讯录未配置异常
}
throw new NotFoundError(
`未在企业 [${corp.name}] 中找到匹配 "${q}" 的员工或管理员。请核对姓名/手机号,或直接传入完整员工工号 (staffId)。`
);
}
export async function handleGenerateCorpLink(
parsed: CliParsedArgs,
runtime: CliRuntime
@@ -27,13 +126,26 @@ export async function handleGenerateCorpLink(
stringOption(parsed.options, ["expires-in", "expiresIn", "expire", "expires", "ttl"]) || 7200;
const pageType = stringOption(parsed.options, ["page-type", "pageType"]) || "home";
const force = booleanOption(parsed.options, ["force", "refresh", "f"]);
const staffInput = stringOption(parsed.options, ["staff", "user", "operator"]);
const persistStaff = booleanOption(parsed.options, ["persist", "save", "save-staff"]);
let resolvedStaff: { staffId: string; staffName?: string } | undefined;
if (staffInput) {
resolvedStaff = await resolveStaffForLink(targetCorp, staffInput);
}
const linkRes = await getCorpProvisionalAuthLink(targetCorp, {
expiresIn,
pageType,
force,
staffId: resolvedStaff?.staffId,
staffName: resolvedStaff?.staffName,
persistStaff,
});
const isSwitched = Boolean(resolvedStaff);
const persistSaved = Boolean(persistStaff && isSwitched);
if (runtime.jsonMode) {
return {
stdout: printJson(
@@ -48,6 +160,8 @@ export async function handleGenerateCorpLink(
token: linkRes.token,
persistent: linkRes.persistent,
method: linkRes.method,
dynamicStaff: isSwitched,
persisted: persistSaved,
},
runtime.outputOptions
),
@@ -60,9 +174,10 @@ export async function handleGenerateCorpLink(
const lines = [
`====== 合思企业 Web 免密登录直达链接 ======`,
` 企业名称 : ${linkRes.corpName} (${linkRes.corpId})`,
` 操作人身份: ${linkRes.staffName ? `${linkRes.staffName} (${linkRes.staffId})` : linkRes.staffId}`,
` 操作人身份: ${linkRes.staffName ? `${linkRes.staffName} (${linkRes.staffId})` : linkRes.staffId}${isSwitched ? " (🔄 动态换签)" : ""}`,
` 签发通道 : ${linkRes.method === "provisional-openapi" ? "OpenAPI 持久化密钥动态签发 (getProvisionalAuth)" : "当前有效会话令牌拼装 (session-token)"}`,
` 过期时间 : ${linkRes.expiresAt}`,
...(persistSaved ? [` 配置持久化: ✅ 已保存为该企业默认操作人`] : []),
` 直达链接 :`,
` ${linkRes.url}`,
``,
+223
View File
@@ -0,0 +1,223 @@
import { describe, expect, it, spyOn, afterEach } from "bun:test";
import { handleWorkflowCommand } from "./workflow/index.js";
import * as helpers from "../helpers.js";
import type { CliRuntime } from "../types.js";
import type { CorpConfig } from "../../core/config/types.js";
const mockCorp: CorpConfig = {
id: "test-corp",
name: "测试企业",
baseUrl: "https://app.ekuaibao.com",
source: "openapi",
credentials: {
accessToken: "mock-token",
corpId: "test-corp",
staffId: "test-corp:STAFF_TEST",
appKey: "test-key",
appSecurity: "test-security",
},
};
const mockRuntime: CliRuntime = {
corpContext: {
listCorps: () => [mockCorp],
getCurrent: () => mockCorp,
switchCorp: () => true,
resolve: () => mockCorp,
} as any,
selectedCorp: mockCorp,
jsonMode: false,
outputOptions: {},
};
describe("CLI - workflow job 执行详情与异常精准透视", () => {
let spies: ReturnType<typeof spyOn>[] = [];
afterEach(() => {
for (const spy of spies) {
spy.mockRestore();
}
spies = [];
});
it("fails when no corp is selected", async () => {
const res = await handleWorkflowCommand(
{
area: "workflow",
action: "job",
args: ["job_123"],
options: {},
raw: ["workflow", "job", "job_123"],
},
{ ...mockRuntime, selectedCorp: null }
);
expect(res.exitCode).toBe(1);
expect(res.stderr).toContain("未选中企业");
});
it("fails when no jobId is provided", async () => {
const res = await handleWorkflowCommand(
{
area: "workflow",
action: "job",
args: [],
options: {},
raw: ["workflow", "job"],
},
mockRuntime
);
expect(res.exitCode).toBe(1);
expect(res.stderr).toContain("用法: hose-use workflow job <jobId>");
});
it("handles workflow job --failed with deep error inspection and inputs/outputs", async () => {
const mockPiperClient = {
get: (url: string) => {
let payload: any = {};
if (url.includes("/execution/level/failed")) {
payload = { number: 1, size: 100, totalPages: 0, totalItems: 0, items: [] };
} else if (url.includes("/execution")) {
payload = [
{
id: "exec_1",
name: "auto_approve",
displayName: "资金调拨自动审批",
type: "flow-approval",
status: "FAILED",
executionTime: 350,
error: { message: "400: 无待办审批事项" },
inputs: { formId: "ZJ-20261014-001368", action: "agree" },
outputs: { code: 400, message: "无待办审批事项" },
},
];
} else if (url.includes("/jobs/job_err")) {
payload = {
id: "job_err",
pipelineId: "pipe_1",
state: "FAILED",
startTime: "2026-10-14 10:00:00",
durationTime: 1200,
};
}
return new Response(JSON.stringify({ code: 200, data: payload }), {
status: 200,
headers: { "content-type": "application/json" },
});
},
};
spies.push(
spyOn(helpers, "createClientsForCorp").mockResolvedValue({
ekbClient: {
get: () => ({ json: async () => [{ id: "plat_1", active: true }] }),
},
easoClient: mockPiperClient,
} as any)
);
spies.push(spyOn(helpers, "createPiperClientForCorp").mockResolvedValue(mockPiperClient as any));
// 文本输出测试
const res = await handleWorkflowCommand(
{
area: "workflow",
action: "job",
args: ["job_err"],
options: { failed: true },
raw: ["workflow", "job", "job_err", "--failed"],
},
mockRuntime
);
expect(res.exitCode).toBe(0);
expect(res.stdout).toContain("Job 异常/失败执行节点透视");
expect(res.stdout).toContain("资金调拨自动审批");
expect(res.stdout).toContain("400: 无待办审批事项");
expect(res.stdout).toContain("ZJ-20261014-001368");
// --json 模式测试
const jsonRes = await handleWorkflowCommand(
{
area: "workflow",
action: "job",
args: ["job_err"],
options: { failed: true, json: true },
raw: ["workflow", "job", "job_err", "--failed", "--json"],
},
{ ...mockRuntime, jsonMode: true }
);
expect(jsonRes.exitCode).toBe(0);
const parsed = JSON.parse(jsonRes.stdout);
expect(parsed.totalFailed).toBe(1);
expect(parsed.failedNodes[0].id).toBe("exec_1");
expect(parsed.failedNodes[0].error.message).toBe("400: 无待办审批事项");
expect(parsed.failedNodes[0].inputs.formId).toBe("ZJ-20261014-001368");
});
it("handles workflow job --node=<name|id> targeting specific execution node", async () => {
const mockPiperClient = {
get: (url: string) => {
let payload: any = {};
if (url.includes("/execution")) {
payload = [
{
id: "node_code",
name: "codeRunner_1",
displayName: "MVEL计算节点",
type: "code",
status: "COMPLETED",
executionTime: 85,
inputs: { expression: "pvTotal * dailyRate" },
outputs: { result: 78787.55 },
},
];
}
return new Response(JSON.stringify({ code: 200, data: payload }), {
status: 200,
headers: { "content-type": "application/json" },
});
},
};
spies.push(
spyOn(helpers, "createClientsForCorp").mockResolvedValue({
ekbClient: {
get: () => ({ json: async () => [{ id: "plat_1", active: true }] }),
},
easoClient: mockPiperClient,
} as any)
);
spies.push(spyOn(helpers, "createPiperClientForCorp").mockResolvedValue(mockPiperClient as any));
const res = await handleWorkflowCommand(
{
area: "workflow",
action: "job",
args: ["job_single"],
options: { node: "MVEL计算" },
raw: ["workflow", "job", "job_single", "--node=MVEL计算"],
},
mockRuntime
);
expect(res.exitCode).toBe(0);
expect(res.stdout).toContain("工作流节点执行详情 [node_code]");
expect(res.stdout).toContain("MVEL计算节点");
expect(res.stdout).toContain("pvTotal * dailyRate");
expect(res.stdout).toContain("78787.55");
// 节点不存在时的错误提示拦截
const notFoundRes = await handleWorkflowCommand(
{
area: "workflow",
action: "job",
args: ["job_single"],
options: { node: "不存在的节点" },
raw: ["workflow", "job", "job_single", "--node=不存在的节点"],
},
mockRuntime
);
expect(notFoundRes.exitCode).toBe(1);
expect(notFoundRes.stderr).toContain("未在 Job [job_single] 的执行树中找到匹配 \"不存在的节点\" 的节点");
});
});
+129 -24
View File
@@ -1,9 +1,13 @@
import {
extractFailureExecutions,
findExecutionNode,
flattenExecutionTree,
getExecutionLogs,
getJob,
getJobExecutionLevel,
getJobExecutionTree,
getJobFailedExecutions,
isTaskExecutionFailed,
listPlatforms,
} from "../../../domains/platform/services.js";
import type { WorkflowTaskExecution } from "../../../domains/platform/types.js";
@@ -101,7 +105,7 @@ export async function handleJob(parsed: CliParsedArgs, runtime: CliRuntime): Pro
if (!jobId) {
return {
stdout: "",
stderr: "用法: hose-use workflow job <jobId> [--failed] [--parent=<executionId>] [--logs=<executionId>]\n",
stderr: "用法: hose-use workflow job <jobId> [--failed] [--node=<name|id>] [--verbose] [--parent=<executionId>] [--logs=<executionId>]\n",
exitCode: 1,
};
}
@@ -111,7 +115,9 @@ export async function handleJob(parsed: CliParsedArgs, runtime: CliRuntime): Pro
const pageSize = numberOption(parsed.options, ["page-size", "pageSize", "size"]) || 100;
const logsExecutionId = stringOption(parsed.options, ["logs", "log", "execution-logs"]);
const parentExecutionId = stringOption(parsed.options, ["parent", "parent-id", "parentId"]);
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"]);
// 1. --logs=<executionId>
if (logsExecutionId) {
@@ -208,21 +214,100 @@ export async function handleJob(parsed: CliParsedArgs, runtime: CliRuntime): Pro
};
}
// 3. --failed
// 3. --node=<name|id>
if (nodeQuery) {
const tree = await getJobExecutionTree(client, jobId);
const matchedNode = findExecutionNode(tree, nodeQuery);
if (!matchedNode) {
return {
stdout: "",
stderr: `未在 Job [${jobId}] 的执行树中找到匹配 "${nodeQuery}" 的节点。请核对节点名称或 Execution ID。\n`,
exitCode: 1,
};
}
if (runtime.jsonMode) {
return {
stdout: printJson({ jobId, node: matchedNode }, runtime.outputOptions),
stderr: "",
exitCode: 0,
};
}
const anyNode = matchedNode as any;
const inputPayload = anyNode.inputs ?? anyNode.form ?? anyNode.params;
const outputPayload = anyNode.outputs ?? anyNode.output ?? anyNode.details;
const lines = [
`====== 工作流节点执行详情 [${matchedNode.id}] (Job: ${jobId}) ======`,
printKeyValue({
"Execution ID": matchedNode.id,
"Parent ID": matchedNode.parentId || "-",
"节点标识 (name)": matchedNode.name || "-",
"节点名称": matchedNode.displayName || matchedNode.label || "-",
"节点类型 (type)": matchedNode.type || "-",
"执行状态 (status)": matchedNode.status || anyNode.state || "-",
"耗时(ms)": String(matchedNode.executionTime ?? anyNode.durationTime ?? "-"),
"开始时间": String(matchedNode.startTime || anyNode.createTime || "-"),
"结束时间": String(matchedNode.endTime || "-"),
"循环路径": matchedNode.currentLoopPath || "-",
...(matchedNode.error?.message ? { "错误信息": matchedNode.error.message } : {}),
}),
];
if (matchedNode.error?.message) {
lines.push("");
lines.push("── ❌ 错误堆栈 / 原因 ──");
lines.push(matchedNode.error.message);
if (anyNode.error?.stack) {
lines.push(anyNode.error.stack);
}
}
if (inputPayload !== undefined) {
lines.push("");
lines.push("── 📥 节点入参报文 (inputs / form) ──");
lines.push(typeof inputPayload === "string" ? inputPayload : JSON.stringify(inputPayload, null, 2));
}
if (outputPayload !== undefined) {
lines.push("");
lines.push("── 📤 节点出参 / 响应结果 (outputs) ──");
lines.push(typeof outputPayload === "string" ? outputPayload : JSON.stringify(outputPayload, null, 2));
}
lines.push("");
return {
stdout: `${lines.join("\n")}\n`,
stderr: "",
exitCode: 0,
};
}
// 4. --failed
if (onlyFailed) {
const [job, failedPage] = await Promise.all([
const [job, tree, failedPage] = await Promise.all([
getJob(client, jobId).catch(() => undefined),
getJobFailedExecutions(client, jobId),
getJobExecutionTree(client, jobId).catch(() => []),
getJobFailedExecutions(client, jobId).catch(() => ({
number: 1,
size: 100,
totalPages: 0,
totalItems: 0,
items: [] as WorkflowTaskExecution[],
})),
]);
const enrichedItems = await enrichFailedExecutions(client, jobId, failedPage.items);
const rawFailed = extractFailureExecutions(tree, failedPage.items);
const enrichedItems = await enrichFailedExecutions(client, jobId, rawFailed);
if (runtime.jsonMode) {
return {
stdout: printJson(
{
jobId,
job: job ?? null,
totalItems: failedPage.totalItems,
items: enrichedItems,
totalFailed: enrichedItems.length,
failedNodes: enrichedItems,
},
runtime.outputOptions
),
@@ -231,34 +316,53 @@ export async function handleJob(parsed: CliParsedArgs, runtime: CliRuntime): Pro
};
}
const rows = enrichedItems.map((item, idx) => [
const rows = enrichedItems.map((item: any, idx) => [
idx + 1,
item.id,
item.parentId || "-",
item.name || "-",
item.type || "-",
item.status || "-",
item.currentLoopPath || "-",
item.error?.message || "-",
item.displayName || item.label || item.type || "-",
item.status || item.state || "-",
String(item.executionTime ?? item.durationTime ?? "-"),
item.error?.message || item.errorMessage || item.outputs?.error || "-",
]);
const formSummaries: string[] = [];
const nodeDetailBlocks: string[] = [];
const shouldExpand = verbose || enrichedItems.length <= 5;
for (const item of enrichedItems) {
if (item.error?.message || item.form !== undefined) {
formSummaries.push(
`\n── ⚠️ 异常节点 [${item.id}] (${item.name || "-"} | status=${item.status} | loop=${item.currentLoopPath || "-"}) ──`
const anyItem = item as any;
const errMsg = item.error?.message || anyItem.errorMessage || anyItem.outputs?.error;
const inputPayload = anyItem.inputs ?? anyItem.form ?? anyItem.params;
const outputPayload = anyItem.outputs ?? anyItem.output ?? anyItem.details;
if (errMsg || inputPayload !== undefined || outputPayload !== undefined) {
nodeDetailBlocks.push(
`\n── ⚠️ 异常节点 [${item.id}] (${item.name || "-"} | ${item.displayName || item.label || item.type || "-"} | status=${item.status || anyItem.state}) ──`
);
if (item.error?.message) {
formSummaries.push(` 错误详情: ${item.error.message}`);
if (errMsg) {
nodeDetailBlocks.push(` ❌ 错误原因: ${errMsg}`);
}
if (item.form !== undefined) {
formSummaries.push(` 表单入参 (form): ${JSON.stringify(item.form)}`);
if (shouldExpand) {
if (inputPayload !== undefined) {
const inStr = typeof inputPayload === "string" ? inputPayload : JSON.stringify(inputPayload, null, 2);
nodeDetailBlocks.push(` 📥 节点入参 (inputs/form):\n${inStr.split("\n").map((l: string) => " " + l).join("\n")}`);
}
if (outputPayload !== undefined) {
const outStr = typeof outputPayload === "string" ? outputPayload : JSON.stringify(outputPayload, null, 2);
nodeDetailBlocks.push(` 📤 节点出参 (outputs/details):\n${outStr.split("\n").map((l: string) => " " + l).join("\n")}`);
}
} else {
if (inputPayload !== undefined) {
nodeDetailBlocks.push(` 📥 节点入参: [已省略,使用 --verbose 查看完整 JSON]`);
}
}
}
}
return {
stdout: [
`====== Job 异常/跳过执行节点明细 (Job: ${jobId}) ======`,
`====== Job 异常/失败执行节点透视 (Job: ${jobId}) ======`,
job
? printKeyValue({
"Job ID": job.id,
@@ -266,16 +370,17 @@ export async function handleJob(parsed: CliParsedArgs, runtime: CliRuntime): Pro
"Job 状态": job.state ?? job.status,
"开始时间": job.startTime || "-",
"耗时(ms)": String(job.durationTime ?? "-"),
"失败节点数": enrichedItems.length,
})
: "",
"",
rows.length
? printTable(
["#", "Execution ID", "Parent ID", "节点标识 (name)", "类型 (type)", "状态 (status)", "循环路径 (currentLoopPath)", "错误原因 (error.message)"],
["#", "Execution ID", "Parent ID", "节点标识 (name)", "节点名称/类型", "状态", "耗时(ms)", "错误原因"],
rows
)
: "未发现异常或报错跳过的执行节点",
...formSummaries,
: "✅ 未发现任何异常或报错失败的执行节点",
...nodeDetailBlocks,
"",
].filter(Boolean).join("\n"),
stderr: "",
+17 -6
View File
@@ -401,6 +401,9 @@ export async function getCorpProvisionalAuthLink(
force?: boolean;
syncLocalSession?: boolean;
enterprisesDir?: string;
staffId?: string;
staffName?: string;
persistStaff?: boolean;
} = {}
): Promise<{
corpId: string;
@@ -418,7 +421,8 @@ export async function getCorpProvisionalAuthLink(
const expiresIn = parseExpiresInSeconds(explicitDuration, 7200);
const pageType = options.pageType || "home";
const corpId = corp.corpId || corp.credentials.corpId;
const staffId = corp.staffId || corp.credentials.staffId;
const targetStaffId = options.staffId || corp.staffId || corp.credentials.staffId;
const targetStaffName = options.staffName || (options.staffId ? undefined : corp.staffName || corp.session?.staffName);
const baseUrl = normalizeBaseUrl(corp.baseUrl || DEFAULT_EKB_BASE_URL);
// 1. 若尚未配置 appKey/appSecurity,先确保会话有效并尝试自动提权提取密钥
@@ -446,7 +450,7 @@ export async function getCorpProvisionalAuthLink(
baseUrl,
openapiToken,
corpId,
staffId,
staffId: targetStaffId,
expiresIn,
pageType,
});
@@ -458,6 +462,13 @@ export async function getCorpProvisionalAuthLink(
if (corp.session) {
corp.session.expTime = provisional.expiresAt;
}
if (options.persistStaff && options.staffId) {
corp.staffId = options.staffId;
corp.credentials.staffId = options.staffId;
if (options.staffName) {
corp.staffName = options.staffName;
}
}
saveCorpConfig(corp, options.enterprisesDir);
invalidateCorpSubdomainTokenCaches(corp);
}
@@ -465,8 +476,8 @@ export async function getCorpProvisionalAuthLink(
return {
corpId,
corpName: corp.name,
staffId: provisional.uid,
staffName: corp.staffName || corp.session?.staffName || undefined,
staffId: provisional.uid || targetStaffId,
staffName: targetStaffName || corp.staffName || corp.session?.staffName || undefined,
url: provisional.url,
token: provisional.token,
expiresIn: provisional.expiresIn,
@@ -511,8 +522,8 @@ export async function getCorpProvisionalAuthLink(
return {
corpId,
corpName: corp.name,
staffId,
staffName: corp.staffName || corp.session?.staffName || undefined,
staffId: targetStaffId,
staffName: targetStaffName || corp.staffName || corp.session?.staffName || undefined,
url,
token: corp.credentials.accessToken,
expiresIn: Math.max(1, Math.round((expMs - Date.now()) / 1000)),
+107
View File
@@ -6,6 +6,7 @@ import {
WorkflowSummary,
WorkflowListAllError,
WorkflowTask,
WorkflowTaskExecution,
WorkflowWithMatches,
TaskMatch,
} from "./types.js";
@@ -213,3 +214,109 @@ export async function findWorkflowsByTaskType(
return { workflows: matched, errors: [...all.errors, ...detailErrors] };
}
/**
* 递归扁平化执行树节点(展开 children / tasks / items 等嵌套数组)
*/
export function flattenExecutionTree(nodes: WorkflowTaskExecution[]): WorkflowTaskExecution[] {
const result: WorkflowTaskExecution[] = [];
function visit(node: any) {
if (!node || typeof node !== "object") return;
result.push(node as WorkflowTaskExecution);
const children = node.children || node.tasks || node.subTasks || node.items;
if (Array.isArray(children)) {
for (const child of children) {
visit(child);
}
}
}
for (const node of nodes) {
visit(node);
}
return result;
}
/**
* 精准判定某个节点是否执行异常或报错
*/
export function isTaskExecutionFailed(node: WorkflowTaskExecution): boolean {
if (!node) return false;
const anyNode = node as any;
if (node.error?.message || anyNode.errorMessage) return true;
if (node.status === "FAILED" || anyNode.state === "FAILED" || anyNode.state === 2) return true;
if (typeof anyNode.errorTaskCount === "number" && anyNode.errorTaskCount > 0) return true;
if (anyNode.outputs && typeof anyNode.outputs === "object" && anyNode.outputs.error) return true;
if (anyNode.output && typeof anyNode.output === "object" && anyNode.output.error) return true;
return false;
}
/**
* 提取并去重执行树中的全部异常失败节点
*/
export function extractFailureExecutions(
tree: WorkflowTaskExecution[],
failedItems: WorkflowTaskExecution[] = []
): WorkflowTaskExecution[] {
const flattened = flattenExecutionTree(tree);
const map = new Map<string, WorkflowTaskExecution>();
for (const item of failedItems) {
if (item?.id) {
map.set(item.id, item);
}
}
for (const node of flattened) {
if (node?.id && isTaskExecutionFailed(node)) {
const existing = map.get(node.id);
if (!existing) {
map.set(node.id, node);
} else {
map.set(node.id, {
...node,
...existing,
error: existing.error ?? node.error,
inputs: existing.inputs ?? (node as any).inputs,
outputs: existing.outputs ?? (node as any).outputs,
});
}
}
}
return Array.from(map.values());
}
/**
* 按 ID、name、displayName 或 label 查找节点
*/
export function findExecutionNode(
tree: WorkflowTaskExecution[],
query: string
): WorkflowTaskExecution | undefined {
const flattened = flattenExecutionTree(tree);
const q = query.trim().toLowerCase();
if (!q) return undefined;
// 1. 精确匹配 ID 或 name
const exact = flattened.find(
(n) =>
n.id?.toLowerCase() === q ||
n.name?.toLowerCase() === q ||
n.displayName?.toLowerCase() === q
);
if (exact) return exact;
// 2. 包含匹配 name、label、displayName
return flattened.find(
(n) =>
n.name?.toLowerCase().includes(q) ||
n.label?.toLowerCase().includes(q) ||
n.displayName?.toLowerCase().includes(q)
);
}
@@ -22,6 +22,12 @@ import {
toggleWorkflow,
updateWorkflow,
} from "./api.js";
import {
extractFailureExecutions,
findExecutionNode,
flattenExecutionTree,
isTaskExecutionFailed,
} from "./services.js";
import { AuthenticationError, EkbApiError } from "../../core/errors.js";
import { WorkflowAlertStore } from "./workflow-alert-store.js";
import { mkdtempSync, readFileSync, rmSync } from "node:fs";
@@ -302,4 +308,92 @@ describe("workflow draft state machine", () => {
const logs = await getExecutionLogs(client, "892809893789696012");
expect(logs[0]?.message).toBe("MVEL script executed");
});
describe("execution tree inspection & failure extraction helpers", () => {
const mockTree: any[] = [
{
id: "node_1",
name: "start_node",
type: "start",
status: "COMPLETED",
children: [
{
id: "node_2",
name: "loop_node",
type: "loop",
status: "COMPLETED",
tasks: [
{
id: "node_3",
name: "approve_node",
displayName: "资金调拨自动审批",
type: "flow-approval",
status: "FAILED",
error: { message: "400: 无待办审批事项" },
inputs: { formId: "ZJ-001368", action: "agree" },
},
],
},
],
},
{
id: "node_4",
name: "notice_node",
displayName: "钉钉通知",
type: "dingtalk",
status: "COMPLETED",
},
];
it("flattenExecutionTree flattens nested children and tasks recursively", () => {
const flattened = flattenExecutionTree(mockTree);
expect(flattened).toHaveLength(4);
expect(flattened.map((n) => n.id)).toEqual(["node_1", "node_2", "node_3", "node_4"]);
});
it("isTaskExecutionFailed identifies various failure indicators", () => {
expect(isTaskExecutionFailed({ id: "1", type: "x", status: "FAILED" })).toBe(true);
expect(
isTaskExecutionFailed({
id: "2",
type: "x",
status: "RUNNING",
error: { message: "timeout", stackTrace: [] },
})
).toBe(true);
expect(isTaskExecutionFailed({ id: "3", type: "x", status: "OK", outputs: { error: "reject" } } as any)).toBe(true);
expect(isTaskExecutionFailed({ id: "4", type: "x", status: "COMPLETED" })).toBe(false);
});
it("extractFailureExecutions merges failures from tree and failed items without duplicates", () => {
const failedPageItems: any[] = [
{
id: "node_3",
name: "approve_node",
status: "FAILED",
outputs: { details: "failed downstream" },
},
];
const failures = extractFailureExecutions(mockTree, failedPageItems);
expect(failures).toHaveLength(1);
expect(failures[0].id).toBe("node_3");
expect(failures[0].error?.message).toBe("400: 无待办审批事项");
expect((failures[0] as any).inputs?.formId).toBe("ZJ-001368");
expect((failures[0] as any).outputs?.details).toBe("failed downstream");
});
it("findExecutionNode matches by id, exact name, or partial display name", () => {
const byId = findExecutionNode(mockTree, "node_3");
expect(byId?.id).toBe("node_3");
const byName = findExecutionNode(mockTree, "approve_node");
expect(byName?.id).toBe("node_3");
const byDisplayName = findExecutionNode(mockTree, "资金调拨");
expect(byDisplayName?.id).toBe("node_3");
const notFound = findExecutionNode(mockTree, "non_existent");
expect(notFound).toBeUndefined();
});
});
});