Merge pull request #97 from yunyingk/feat/observable-ops-phase1
feat(ops): add dynamic staff link switching and deep failed job inspection (Phase 1)
This commit is contained in:
17 files changed
+898
-81
No files matched your search
@@ -253,7 +253,7 @@ async function handleStatus(parsed: CliParsedArgs, runtime: CliRuntime): Promise
|
||||
: "✅ 统一认证主账号自动换票"
|
||||
: "⚪ 短期会话",
|
||||
"Token 有效性": sessionValid ? "✅ 有效 (已通过 Session 验证)" : "❌ 无效或未连接",
|
||||
"Token 过期时间": formatExpiresAt(currentCorp?.auth?.expiresAt || currentCorp?.session?.expTime, isPersistent),
|
||||
"Token 过期时间": formatExpiresAt(currentCorp?.auth?.expiresAt || currentCorp?.session?.expTime, isPersistent, hasOpenApi ? "openapi" : currentCorp?.source),
|
||||
};
|
||||
|
||||
if (currentCorp?.session) {
|
||||
|
||||
@@ -135,7 +135,7 @@ export async function handleContextCommand(
|
||||
` 当前操作员工 : ${corpStaffId}`,
|
||||
` 员工真实姓名 : ${corpStaffName}`,
|
||||
` 凭证来源类型 : ${currentCorp ? formatSourceLabel(currentCorp.source, hasOpenApiPersistentCredentials(currentCorp)) : "-"}`,
|
||||
` 凭证有效状态 : ${currentCorp ? formatExpiresAt(corpExpiresAt, currentPersistent) : "-"}`,
|
||||
` 凭证有效状态 : ${currentCorp ? formatExpiresAt(corpExpiresAt, currentPersistent, hasOpenApiPersistentCredentials(currentCorp) ? "openapi" : currentCorp.source) : "-"}`,
|
||||
` 主站 BaseURL : ${currentCorp?.baseUrl || "-"}`,
|
||||
` 已配置企业总数: ${allCorps.length} 家 (有效: ${validCorps.length} 家, 已过期: ${expiredCorps.length} 家)`,
|
||||
` AI PRO 规约库 : ${scopesStr}`,
|
||||
|
||||
@@ -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(
|
||||
{
|
||||
|
||||
@@ -55,7 +55,7 @@ export async function handleCurrent(parsed: CliParsedArgs, runtime: CliRuntime):
|
||||
"员工姓名": current.staffName || current.session?.staffName || "-",
|
||||
"凭证来源": formatSourceLabel(current.source, hasOpenApi),
|
||||
"持久化状态": isPersistent ? (hasOpenApi ? `✅ 已配置 OpenAPI 持久化密钥 (${current.credentials.appKey})` : "✅ 已绑定统一认证主账号") : "⚪ 短期临时会话",
|
||||
"Token 过期时间": formatExpiresAt(current.auth?.expiresAt || current.session?.expTime, isPersistent),
|
||||
"Token 过期时间": formatExpiresAt(current.auth?.expiresAt || current.session?.expTime, isPersistent, hasOpenApi ? "openapi" : current.source),
|
||||
"所属账号": current.accountId || "-",
|
||||
"主站地址": current.baseUrl || "https://app.ekuaibao.com",
|
||||
"适用上下文": "同时作为 hose-use 与 hose-aipro 的统一执行环境",
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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}`,
|
||||
``,
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { canRefreshCorpAccessToken } from "../../../core/auth/login.js";
|
||||
import { stringOption } from "../../parser.js";
|
||||
import { printJson, printTable, formatExpiresAt } from "../../printer.js";
|
||||
import { printJson, printTable, formatExpiresAt, formatSourceLabel } from "../../printer.js";
|
||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js";
|
||||
|
||||
const FIELD_LABEL_MAP: Record<string, string> = {
|
||||
@@ -30,19 +30,26 @@ export async function handleSearch(parsed: CliParsedArgs, runtime: CliRuntime):
|
||||
: null;
|
||||
|
||||
const normalizedCorps = rawCorps
|
||||
? rawCorps.map((c) => ({
|
||||
id: c.id,
|
||||
name: c.name,
|
||||
corpId: c.corpId || c.credentials?.corpId || c.id,
|
||||
staffId: c.staffId || c.credentials?.staffId || "",
|
||||
staffName: c.staffName || c.session?.staffName || "",
|
||||
accountId: c.accountId || "",
|
||||
source: c.source || "manual",
|
||||
baseUrl: c.baseUrl,
|
||||
current: c.id === runtime.selectedCorp?.id,
|
||||
expiresAt: c.auth?.expiresAt || (c.session?.expTime ?? undefined),
|
||||
persistent: canRefreshCorpAccessToken(c),
|
||||
}))
|
||||
? rawCorps.map((c) => {
|
||||
const hasOpenApi = Boolean(
|
||||
(c.credentials?.appKey || c.auth?.appKey) &&
|
||||
(c.credentials?.appSecurity || c.auth?.appSecurity)
|
||||
);
|
||||
return {
|
||||
id: c.id,
|
||||
name: c.name,
|
||||
corpId: c.corpId || c.credentials?.corpId || c.id,
|
||||
staffId: c.staffId || c.credentials?.staffId || "",
|
||||
staffName: c.staffName || c.session?.staffName || "",
|
||||
accountId: c.accountId || "",
|
||||
source: c.source || "manual",
|
||||
baseUrl: c.baseUrl,
|
||||
current: c.id === runtime.selectedCorp?.id,
|
||||
expiresAt: c.auth?.expiresAt || (c.session?.expTime ?? undefined),
|
||||
persistent: canRefreshCorpAccessToken(c),
|
||||
hasOpenApi,
|
||||
};
|
||||
})
|
||||
: runtime.corpContext.listCorps().map((c) => ({
|
||||
id: c.id,
|
||||
name: c.name,
|
||||
@@ -55,6 +62,7 @@ export async function handleSearch(parsed: CliParsedArgs, runtime: CliRuntime):
|
||||
current: c.current || c.id === runtime.selectedCorp?.id,
|
||||
expiresAt: c.expiresAt,
|
||||
persistent: c.persistent,
|
||||
hasOpenApi: c.hasOpenApi,
|
||||
}));
|
||||
|
||||
const matches: Array<typeof normalizedCorps[number] & { matchedFields: string[] }> = [];
|
||||
@@ -134,7 +142,7 @@ export async function handleSearch(parsed: CliParsedArgs, runtime: CliRuntime):
|
||||
m.staffName ? (m.matchedFields.includes("staffName") ? `[${m.staffName}]` : m.staffName) : "-",
|
||||
m.accountId ? (m.matchedFields.includes("accountId") ? `[${m.accountId}]` : m.accountId) : "-",
|
||||
matchLabels.map((l) => `命中${l}`).join(", "),
|
||||
formatExpiresAt(m.expiresAt, m.persistent),
|
||||
formatExpiresAt(m.expiresAt, m.persistent, m.hasOpenApi ? "openapi" : m.source),
|
||||
];
|
||||
});
|
||||
|
||||
@@ -176,8 +184,8 @@ export async function handleList(parsed: CliParsedArgs, runtime: CliRuntime): Pr
|
||||
c.id,
|
||||
c.name,
|
||||
c.staffId,
|
||||
c.source || "manual",
|
||||
formatExpiresAt(c.expiresAt, c.persistent),
|
||||
formatSourceLabel(c.source, c.hasOpenApi),
|
||||
formatExpiresAt(c.expiresAt, c.persistent, c.hasOpenApi ? "openapi" : c.source),
|
||||
c.accountId || "-",
|
||||
]);
|
||||
|
||||
|
||||
@@ -110,7 +110,7 @@ export async function handleProbeCommand(
|
||||
? `✅ OpenAPI 持久化密钥 (${currentCorp.credentials.appKey})`
|
||||
: "✅ 统一认证主账号自动换票"
|
||||
: "⚪ 短期会话",
|
||||
"Token 过期时间": formatExpiresAt(currentCorp.auth?.expiresAt || currentCorp.session?.expTime, isPersistent),
|
||||
"Token 过期时间": formatExpiresAt(currentCorp.auth?.expiresAt || currentCorp.session?.expTime, isPersistent, hasOpenApi ? "openapi" : currentCorp.source),
|
||||
"主站 Session 连通": (results.ekbSession as any).status === "ok" ? "🟢 正常" : "🔴 异常",
|
||||
"EASO 引擎鉴权换票": (results.easoToken as any).status === "ok" ? "🟢 握手成功" : "🔴 失败",
|
||||
"自建应用扫描": (results.platformAccess as any).status === "ok" ? `🟢 可访问 (${(results.platformAccess as any).totalPlatforms} 个自建应用)` : "🔴 失败",
|
||||
|
||||
@@ -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] 的执行树中找到匹配 \"不存在的节点\" 的节点");
|
||||
});
|
||||
});
|
||||
@@ -38,10 +38,14 @@ export async function handleLogs(parsed: CliParsedArgs, runtime: CliRuntime): Pr
|
||||
endTime: stringOption(parsed.options, ["end-time", "endTime"]),
|
||||
});
|
||||
const hasErrorFilter = booleanOption(parsed.options, ["has-error", "hasError", "errors"]);
|
||||
const isJobError = (job: any): boolean => {
|
||||
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(
|
||||
(job) => job.hasError === true || job.errorTaskCount > 0 || job.state === "FAILED"
|
||||
)
|
||||
? rawResult.jobList.filter(isJobError)
|
||||
: rawResult.jobList;
|
||||
const result = hasErrorFilter
|
||||
? { ...rawResult, jobList: filteredJobList }
|
||||
@@ -49,15 +53,15 @@ export async function handleLogs(parsed: CliParsedArgs, runtime: CliRuntime): Pr
|
||||
|
||||
if (runtime.jsonMode) return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
|
||||
const rows = result.jobList.map((job, idx) => [
|
||||
const rows = result.jobList.map((job: any, idx) => [
|
||||
idx + 1,
|
||||
job.id,
|
||||
job.state,
|
||||
job.successTaskCount,
|
||||
job.errorTaskCount,
|
||||
job.hasError || job.errorTaskCount > 0 ? "⚠️ 是 (true)" : "否 (false)",
|
||||
job.jobId || job.id || "-",
|
||||
job.status || (job.state === 0 ? "COMPLETED" : String(job.state ?? "-")),
|
||||
job.successTaskCount ?? 0,
|
||||
job.errorTaskCount ?? 0,
|
||||
isJobError(job) ? "⚠️ 包含错误" : "正常",
|
||||
job.durationTime ?? "-",
|
||||
job.startTime || "-",
|
||||
job.executeTime || job.startTime || "-",
|
||||
]);
|
||||
const tableStr = rows.length
|
||||
? printTable(
|
||||
|
||||
@@ -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: "",
|
||||
|
||||
@@ -7,6 +7,8 @@ import {
|
||||
protectLargeOutput,
|
||||
printJson,
|
||||
redactSensitiveText,
|
||||
formatSourceLabel,
|
||||
formatExpiresAt,
|
||||
} from "./printer.js";
|
||||
|
||||
describe("cli/printer - 上下文防爆与敏感脱敏", () => {
|
||||
@@ -114,4 +116,60 @@ describe("cli/printer - 上下文防爆与敏感脱敏", () => {
|
||||
expect(savedContent[0].id).toBe("id-0");
|
||||
});
|
||||
});
|
||||
|
||||
describe("formatSourceLabel 4大凭证类别规范格式化", () => {
|
||||
test("企业开放接口 (OpenAPI 密钥)", () => {
|
||||
expect(formatSourceLabel("openapi")).toBe("企业开放接口 (OpenAPI 密钥)");
|
||||
expect(formatSourceLabel("account", true)).toBe("企业开放接口 (OpenAPI 密钥)");
|
||||
expect(formatSourceLabel("link", true)).toBe("企业开放接口 (OpenAPI 密钥)");
|
||||
});
|
||||
|
||||
test("个人账号凭证 (手机号)", () => {
|
||||
expect(formatSourceLabel("account")).toBe("个人账号凭证 (手机号)");
|
||||
});
|
||||
|
||||
test("合思协助平台授权链接 (协助链接)", () => {
|
||||
expect(formatSourceLabel("link")).toBe("合思协助平台授权链接 (协助链接)");
|
||||
expect(formatSourceLabel("assist")).toBe("合思协助平台授权链接 (协助链接)");
|
||||
});
|
||||
|
||||
test("网页临时抓包凭证 (Cookie)", () => {
|
||||
expect(formatSourceLabel("curl")).toBe("网页临时抓包凭证 (Cookie)");
|
||||
expect(formatSourceLabel("browser")).toBe("网页临时抓包凭证 (Cookie)");
|
||||
expect(formatSourceLabel("f12")).toBe("网页临时抓包凭证 (Cookie)");
|
||||
});
|
||||
|
||||
test("兜底处理", () => {
|
||||
expect(formatSourceLabel("manual")).toBe("手动配置");
|
||||
expect(formatSourceLabel("other")).toBe("其他 (other)");
|
||||
expect(formatSourceLabel(undefined)).toBe("未知来源");
|
||||
});
|
||||
});
|
||||
|
||||
describe("formatExpiresAt 过期状态精准描述", () => {
|
||||
test("长期有效凭据", () => {
|
||||
expect(formatExpiresAt(undefined, true, "openapi")).toBe("长期有效 (OpenAPI 密钥)");
|
||||
expect(formatExpiresAt(0, false)).toBe("长期有效 / 服务端未显式限制");
|
||||
});
|
||||
|
||||
test("已过期但具备自动续期能力的凭据", () => {
|
||||
const pastTime = Date.now() - 3600000;
|
||||
expect(formatExpiresAt(pastTime, true, "account")).toContain("(🔄 随主账号自动换票)");
|
||||
expect(formatExpiresAt(pastTime, true, "openapi")).toContain("(🔄 OpenAPI 密钥自动续期)");
|
||||
expect(formatExpiresAt(pastTime, true)).toContain("(🔄 自动续期)");
|
||||
});
|
||||
|
||||
test("已过期且不可续期的凭据精准告警", () => {
|
||||
const pastTime = Date.now() - 3600000;
|
||||
expect(formatExpiresAt(pastTime, false, "link")).toContain("(⚠️ 协助授权已失效)");
|
||||
expect(formatExpiresAt(pastTime, false, "curl")).toContain("(⚠️ Cookie 已失效)");
|
||||
expect(formatExpiresAt(pastTime, false, "manual")).toContain("(⚠️ 已过期)");
|
||||
});
|
||||
|
||||
test("未来有效期的剩余提示", () => {
|
||||
const futureMins = Date.now() + 30 * 60000;
|
||||
expect(formatExpiresAt(futureMins, true, "account")).toContain("支持主账号自动换票");
|
||||
expect(formatExpiresAt(futureMins, true, "openapi")).toContain("支持 OpenAPI 密钥自动续期");
|
||||
});
|
||||
});
|
||||
});
|
||||
+58
-18
@@ -42,48 +42,88 @@ export function printJson(data: unknown, options: OutputOptions = {}): string {
|
||||
}
|
||||
|
||||
export function formatSourceLabel(source?: string, persistentOpenApi?: boolean): string {
|
||||
const suffix = persistentOpenApi && source !== "openapi" ? " + OpenAPI 持久化密钥" : "";
|
||||
if (persistentOpenApi || source === "openapi") {
|
||||
return "企业开放接口 (OpenAPI 密钥)";
|
||||
}
|
||||
switch (source) {
|
||||
case "openapi":
|
||||
return "开放平台持久化密钥 (OpenAPI AppKey)";
|
||||
case "assist":
|
||||
return `官方协助/代客平台 (Assist Platform)${suffix}`;
|
||||
case "account":
|
||||
return `统一认证中心 (IDP 账密/短信)${suffix}`;
|
||||
case "browser":
|
||||
return `浏览器会话同步 (WebBridge)${suffix}`;
|
||||
return "个人账号凭证 (手机号)";
|
||||
case "assist":
|
||||
case "link":
|
||||
return `协助/免密链接导入 (Assistance Link)${suffix}`;
|
||||
return "合思协助平台授权链接 (协助链接)";
|
||||
case "browser":
|
||||
case "curl":
|
||||
case "f12":
|
||||
return `cURL 抓包导入 (cURL/F12)${suffix}`;
|
||||
return "网页临时抓包凭证 (Cookie)";
|
||||
case "manual":
|
||||
return `手动配置${suffix}`;
|
||||
return "手动配置";
|
||||
default:
|
||||
return (source || "未知来源") + suffix;
|
||||
return source ? `其他 (${source})` : "未知来源";
|
||||
}
|
||||
}
|
||||
|
||||
export function formatExpiresAt(expiresAt?: number | null, persistent?: boolean): string {
|
||||
if (!expiresAt || expiresAt <= 0) return "长期有效 / 服务端未显式限制";
|
||||
export function formatExpiresAt(
|
||||
expiresAt?: number | null,
|
||||
persistent?: boolean,
|
||||
source?: string
|
||||
): string {
|
||||
if (!expiresAt || expiresAt <= 0) {
|
||||
if (source === "openapi") {
|
||||
return "长期有效 (OpenAPI 密钥)";
|
||||
}
|
||||
return "长期有效 / 服务端未显式限制";
|
||||
}
|
||||
const diffMs = expiresAt - Date.now();
|
||||
const dateStr = new Date(expiresAt).toLocaleString("zh-CN", { hour12: false });
|
||||
if (diffMs <= 0) {
|
||||
if (persistent) {
|
||||
return `${dateStr} (🔄 持久化密钥自动续期)`;
|
||||
if (source === "account") {
|
||||
return `${dateStr} (🔄 随主账号自动换票)`;
|
||||
}
|
||||
if (source === "openapi") {
|
||||
return `${dateStr} (🔄 OpenAPI 密钥自动续期)`;
|
||||
}
|
||||
return `${dateStr} (🔄 自动续期)`;
|
||||
}
|
||||
if (source === "link" || source === "assist") {
|
||||
return `${dateStr} (⚠️ 协助授权已失效)`;
|
||||
}
|
||||
if (source === "curl" || source === "browser" || source === "f12") {
|
||||
return `${dateStr} (⚠️ Cookie 已失效)`;
|
||||
}
|
||||
return `${dateStr} (⚠️ 已过期)`;
|
||||
}
|
||||
const diffMins = Math.floor(diffMs / 60000);
|
||||
if (diffMins < 60) {
|
||||
return `${dateStr} (约剩余 ${diffMins} 分钟${persistent ? ",支持自动续期" : ""})`;
|
||||
const renewSuffix = persistent
|
||||
? source === "account"
|
||||
? ",支持主账号自动换票"
|
||||
: source === "openapi"
|
||||
? ",支持 OpenAPI 密钥自动续期"
|
||||
: ",支持自动续期"
|
||||
: "";
|
||||
return `${dateStr} (约剩余 ${diffMins} 分钟${renewSuffix})`;
|
||||
}
|
||||
const diffHours = (diffMs / 3600000).toFixed(1);
|
||||
if (Number(diffHours) < 24) {
|
||||
return `${dateStr} (约剩余 ${diffHours} 小时${persistent ? ",支持自动续期" : ""})`;
|
||||
const renewSuffix = persistent
|
||||
? source === "account"
|
||||
? ",支持主账号自动换票"
|
||||
: source === "openapi"
|
||||
? ",支持 OpenAPI 密钥自动续期"
|
||||
: ",支持自动续期"
|
||||
: "";
|
||||
return `${dateStr} (约剩余 ${diffHours} 小时${renewSuffix})`;
|
||||
}
|
||||
const diffDays = Math.floor(diffMs / 86400000);
|
||||
return `${dateStr} (约剩余 ${diffDays} 天)`;
|
||||
const renewSuffix = persistent
|
||||
? source === "account"
|
||||
? ",支持主账号自动换票"
|
||||
: source === "openapi"
|
||||
? ",支持 OpenAPI 密钥自动续期"
|
||||
: ""
|
||||
: "";
|
||||
return `${dateStr} (约剩余 ${diffDays} 天${renewSuffix})`;
|
||||
}
|
||||
|
||||
export function printKeyValue(pairs: Record<string, unknown>): string {
|
||||
|
||||
@@ -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)),
|
||||
|
||||
@@ -20,6 +20,7 @@ export interface CorpSummary {
|
||||
current: boolean;
|
||||
expiresAt?: number;
|
||||
persistent?: boolean;
|
||||
hasOpenApi?: boolean;
|
||||
}
|
||||
|
||||
export function resolveCorpConfig(
|
||||
@@ -172,6 +173,7 @@ export class CorpContext {
|
||||
current: corp.id === this.current?.id,
|
||||
expiresAt: getCorpExpiresAt(corp),
|
||||
persistent: hasOpenApiKeys || hasAccountBinding,
|
||||
hasOpenApi: hasOpenApiKeys,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
@@ -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();
|
||||
});
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user