feat(workflow): 支持节点只读透视与样本固化,规范企业切换上下文持久化

- skill: 补充终止节点物理断点与样本固化 (Stop Barrier & Sample Pinning) 最佳实践
- config: 修复 switchCorp / enter --switch 持久化写入 defaultCorpId 与激活 stateful 模式
- workflow node: 新增 inspect (探针透视配置/样本/执行) 与 sample-save (一键固化出参至 sampleData 并刷新选择树)
- workflow test: 新增 --save-sample 选项,调测通过后自动将产生出参的节点固化为 sampleData
- parser/metadata: 注册 save-sample 选项词汇表,补充单测 workflow-node-sample-inspect.test.ts
This commit is contained in:
gitea committed 2026-11-24 11:45:46 +08:00
1 parent 5e59c835f1
commit 86a02b82b7
7 files changed
+949 -11

No files matched your search

+1 -1
View File
@@ -340,7 +340,7 @@ export const COMMAND_METADATA: Record<string, CliCommandMetadata> = {
"outbound-message": "outbound"
},
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 full has-error hasError in-place inPlace includeDetail is-test json none once publish snapshot v value-json valueJson verbose with-tasks withTasks timeline progress steps", "boolean"), ...flagList("a admin-key adminKey after app app-id appId b bill body c choose-serialization code code-file container count d data desc description display display-name displayName 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 json-file keyword l label limit log logs mapping mapping-file max-jobs maxJobs max-pages maxPages message-type n name node node-id nodeId nodes offset output output-file outputFile p page page-limit page-size pageSize parent parent-id parentId password path payload pipeline pipeline-id pipelineId platform platform-id platformId pwd q query record s sample sample-id sampleId seconds set size sleep-time sleepTime sn snapshot1 snapshot2 snapshotA snapshotB source start 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 full has-error hasError in-place inPlace includeDetail is-test json none once publish save-sample saveSample save-samples saveSamples snapshot v value-json valueJson verbose with-tasks withTasks timeline progress steps", "boolean"), ...flagList("a admin-key adminKey after app app-id appId b bill body c choose-serialization code code-file container count d data desc description display display-name displayName 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 json-file keyword l label limit log logs mapping mapping-file max-jobs maxJobs max-pages maxPages message-type n name node node-id nodeId nodes offset output output-file outputFile p page page-limit page-size pageSize parent parent-id parentId password path payload pipeline pipeline-id pipelineId platform platform-id platformId pwd q query record s sample sample-id sampleId seconds set size sleep-time sleepTime sn snapshot1 snapshot2 snapshotA snapshotB source start 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": {
@@ -0,0 +1,478 @@
import { describe, it, expect, beforeEach, afterEach, spyOn } from "bun:test";
import { handleWorkflowCommand } from "./workflow/index.js";
import * as helpers from "./workflow/shared.js";
import { CorpContext } from "../../core/config/manager.js";
import type { CorpConfig } from "../../core/config/types.js";
import type { CliRuntime } from "../types.js";
const mockCorp: CorpConfig = {
id: "ID01ofWoOC1wiX",
name: "沈玥妍测试企业",
baseUrl: "https://app.ekuaibao.com",
cluster: "app",
source: "link",
credentials: {
accessToken: "test-token",
corpId: "ID01ofWoOC1wiX",
staffId: "ID01ofWoOC1wiX:ID01KsDgHaH5nN",
},
env: "test",
isTest: true,
};
describe("CLI - workflow node inspect 与 sample-save (只读探针与样本一键固化)", () => {
let spies: any[] = [];
let mockRuntime: CliRuntime;
beforeEach(() => {
spies = [];
const corpContext = new CorpContext([mockCorp], { stateful: true, defaultCorpId: mockCorp.id });
mockRuntime = {
corpContext,
selectedCorp: mockCorp,
jsonMode: false,
outputOptions: {},
};
});
afterEach(() => {
for (const spy of spies) {
spy.mockRestore();
}
spies = [];
});
it("workflow node inspect: 成功透视节点配置、已存样本与历史调试出参", async () => {
const mockTasks = [
{
name: "trigger_1",
type: "ekuaibao-ebot-trigger",
label: "EBOT触发",
orderIndex: 0,
levelIndex: [0],
status: "active",
},
{
name: "action_calc_1",
type: "code",
label: "代码节点",
displayName: "时间转换节点",
orderIndex: 1,
levelIndex: [1],
status: "active",
code: "result = ['minute': '2026-11-19 20:59'];\nreturn result;",
sampleData: {
minute: "2026-11-19 20:59",
},
},
];
const mockDetail = {
id: "wf_inspect_test",
label: "测试工作流",
state: 0,
tasks: mockTasks,
};
const mockExecutionTree = [
{
id: "exec_1",
name: "action_calc_1",
status: "COMPLETED",
executionTime: 8,
output: {
minute: "2026-11-19 20:59",
timestampMs: 1795093140000,
},
},
];
const mockClient = {
get: (url: string) => {
if (url.includes("api/easo/pipelines/wf_inspect_test/log")) {
return {
text: async () => JSON.stringify({ code: 200 }),
json: async () => ({
code: 200,
data: {
totalCount: 1,
items: [{ id: "job_test_100", status: "COMPLETED" }],
},
}),
};
}
if (url.includes("api/easo/pipelines/wf_inspect_test")) {
return {
text: async () => JSON.stringify({ code: 200 }),
json: async () => ({ code: 200, data: mockDetail }),
};
}
if (url.includes("api/easo/jobs/job_test_100/execution")) {
return {
text: async () => JSON.stringify({ code: 200 }),
json: async () => ({ code: 200, data: mockExecutionTree }),
};
}
return {
text: async () => JSON.stringify({ code: 200 }),
json: async () => ({ code: 200, data: null }),
};
},
};
spies.push(
spyOn(helpers, "createWorkflowDetailClient").mockResolvedValue({
client: mockClient as any,
clients: {} as any,
platformId: undefined,
})
);
// 1. 终端文本透视
const resText = await handleWorkflowCommand(
{
area: "workflow",
action: "node",
args: ["inspect", "wf_inspect_test", "action_calc_1"],
options: {},
raw: ["workflow", "node", "inspect", "wf_inspect_test", "action_calc_1"],
},
mockRuntime
);
expect(resText.exitCode).toBe(0);
expect(resText.stdout).toContain("工作流节点只读探针");
expect(resText.stdout).toContain("action_calc_1");
expect(resText.stdout).toContain("时间转换节点");
expect(resText.stdout).toContain("已固化样本");
expect(resText.stdout).toContain("最近一次调试执行出参");
expect(resText.stdout).toContain("job_test_100");
expect(resText.stdout).toContain("1795093140000");
// 2. JSON 模式结构化输出
mockRuntime.jsonMode = true;
const resJson = await handleWorkflowCommand(
{
area: "workflow",
action: "node",
args: ["inspect", "wf_inspect_test", "action_calc_1"],
options: {},
raw: ["workflow", "node", "inspect", "wf_inspect_test", "action_calc_1", "--json"],
},
mockRuntime
);
expect(resJson.exitCode).toBe(0);
const parsedJson = JSON.parse(resJson.stdout);
expect(parsedJson.sampleData.minute).toBe("2026-11-19 20:59");
expect(parsedJson.executionProbe.jobId).toBe("job_test_100");
expect(parsedJson.executionProbe.output.timestampMs).toBe(1795093140000);
});
it("workflow node sample-save: 支持 dry-run 预览并一键固化出参至节点 sampleData", async () => {
let savedTasks: any = null;
let choosesRefreshed = false;
const mockTasks = [
{
name: "action_target_node",
type: "code",
label: "代码节点",
orderIndex: 0,
levelIndex: [0],
status: "active",
},
];
const mockDetail = {
id: "wf_save_sample_test",
label: "样本固化测试流",
version: "1.0.0",
tasksVersion: 1,
state: 0,
tasks: mockTasks,
};
const mockExecutionTree = [
{
id: "exec_node_target",
name: "action_target_node",
status: "COMPLETED",
output: {
formattedDate: "2026-11-24 11:30",
rangeSec: "2026-11-24 11:30:00 ~ 2026-11-24 12:00:00",
},
},
];
const mockClient = {
get: (url: string) => {
if (url.includes("api/easo/pipelines/wf_save_sample_test")) {
return { json: async () => ({ code: 200, data: mockDetail }) };
}
if (url.includes("api/easo/jobs/job_custom_999/execution")) {
return { json: async () => ({ code: 200, data: mockExecutionTree }) };
}
return { json: async () => ({ code: 200, data: null }) };
},
put: (url: string, opts: any) => {
if (url.endsWith("/chooses")) {
choosesRefreshed = true;
return {
text: async () => JSON.stringify({ code: 200, data: [] }),
json: async () => ({ code: 200, data: [] }),
};
}
if (url.includes("api/easo/pipelines/wf_save_sample_test")) {
savedTasks = opts.json.tasks;
return {
text: async () =>
JSON.stringify({
code: 200,
data: {
...mockDetail,
...opts.json,
tasksVersion: 2,
},
}),
json: async () => ({
code: 200,
data: {
...mockDetail,
...opts.json,
tasksVersion: 2,
},
}),
};
}
return {
text: async () => JSON.stringify({ code: 200, data: null }),
json: async () => ({ code: 200, data: null }),
};
},
};
spies.push(
spyOn(helpers, "createWorkflowDetailClient").mockResolvedValue({
client: mockClient as any,
clients: {} as any,
platformId: undefined,
})
);
// 1. Dry-run 预览
const dryRes = await handleWorkflowCommand(
{
area: "workflow",
action: "node",
args: ["sample-save", "wf_save_sample_test", "action_target_node"],
options: { dryRun: true, job: "job_custom_999" },
raw: ["workflow", "node", "sample-save", "wf_save_sample_test", "action_target_node", "--job=job_custom_999", "--dry-run"],
},
mockRuntime
);
expect(dryRes.exitCode).toBe(0);
expect(dryRes.stdout).toContain("[DRY-RUN]");
expect(dryRes.stdout).toContain("固化节点样本数据 (sampleData)");
expect(savedTasks).toBeNull();
// 2. 确认执行
const execRes = await handleWorkflowCommand(
{
area: "workflow",
action: "node",
args: ["sample-save", "wf_save_sample_test", "action_target_node"],
options: { yes: true, job: "job_custom_999" },
raw: ["workflow", "node", "sample-save", "wf_save_sample_test", "action_target_node", "--job=job_custom_999", "--yes"],
},
mockRuntime
);
expect(execRes.exitCode).toBe(0);
expect(execRes.stdout).toContain("样本数据 (sampleData) 固化成功");
expect(execRes.stdout).toContain("固化字段数 : 2 个属性");
expect(savedTasks).not.toBeNull();
expect(savedTasks[0].sampleData.formattedDate).toBe("2026-11-24 11:30");
expect(choosesRefreshed).toBe(true);
});
it("workflow test --save-sample: 调试通过后自动固化执行出参为节点 sampleData", async () => {
let savedTasks: any = null;
let choosesRefreshed = false;
const mockTasks = [
{
name: "trigger_1",
type: "ekuaibao-flowform-trigger",
label: "单据触发",
orderIndex: 0,
levelIndex: [0],
status: "active",
},
{
name: "action_code_date",
type: "code",
label: "代码节点",
orderIndex: 1,
levelIndex: [1],
status: "active",
code: "return ['minute': '2026-11-24 11:35'];",
},
];
const mockDetail = {
id: "wf_test_save_sample",
label: "自动保存样本流程",
version: "1.0.0",
tasksVersion: 1,
state: 0,
tasks: mockTasks,
};
const mockClient = {
post: (url: string) => {
if (url.includes("debugSource")) {
return {
json: async () => ({
code: 200,
data: {
type: "flowForm",
total: 1,
items: [{ id: "S26000001", title: "测试单据", flowState: "审批中" }],
},
}),
};
}
if (url.includes("api/easo/jobs")) {
return {
json: async () => ({
code: 200,
data: "job_auto_sample_123",
}),
};
}
return { json: async () => ({ code: 200, data: null }) };
},
get: (url: string) => {
if (url.includes("/level/failed")) return { json: async () => ({ code: 200, data: [] }) };
if (url.includes("execution")) {
return {
json: async () => ({
code: 200,
data: [
{
id: "e1",
name: "trigger_1",
label: "单据触发",
type: "ekuaibao-flowform-trigger",
status: "COMPLETED",
executionTime: 10,
},
{
id: "e2",
name: "action_code_date",
label: "代码节点",
type: "code",
status: "COMPLETED",
executionTime: 5,
output: {
minute: "2026-11-24 11:35",
timestampMs: 1795093140000,
},
},
],
}),
};
}
if (url.includes("api/easo/jobs/job_auto_sample_123")) {
return {
json: async () => ({
code: 200,
data: {
id: "job_auto_sample_123",
pipelineId: "wf_test_save_sample",
status: "COMPLETED",
startTime: 1795490000000,
endTime: 1795490001000,
executionTime: 1000,
},
}),
};
}
if (url.includes("api/easo/pipelines/wf_test_save_sample")) {
return {
json: async () => ({
code: 200,
data: mockDetail,
}),
};
}
return { json: async () => ({ code: 200, data: null }) };
},
put: (url: string, opts: any) => {
if (url.endsWith("/chooses")) {
choosesRefreshed = true;
return {
text: async () => JSON.stringify({ code: 200, data: [] }),
json: async () => ({ code: 200, data: [] }),
};
}
if (url.includes("api/easo/pipelines/wf_test_save_sample")) {
savedTasks = opts.json.tasks;
return {
text: async () =>
JSON.stringify({
code: 200,
data: {
...mockDetail,
...opts.json,
tasksVersion: 2,
},
}),
json: async () => ({
code: 200,
data: {
...mockDetail,
...opts.json,
tasksVersion: 2,
},
}),
};
}
return {
text: async () => JSON.stringify({ code: 200, data: null }),
json: async () => ({ code: 200, data: null }),
};
},
};
spies.push(
spyOn(helpers, "createWorkflowDetailClient").mockResolvedValue({
client: mockClient as any,
clients: {} as any,
platformId: undefined,
})
);
const testRes = await handleWorkflowCommand(
{
area: "workflow",
action: "test",
args: ["wf_test_save_sample"],
options: { flow: "S26000001", saveSample: true, yes: true },
raw: ["workflow", "test", "wf_test_save_sample", "--flow=S26000001", "--save-sample", "--yes"],
},
mockRuntime
);
expect(testRes.exitCode).toBe(0);
expect(testRes.stdout).toContain("工作流自动化调测报告");
expect(testRes.stdout).toContain("样本数据自动固化");
expect(testRes.stdout).toContain("action_code_date");
expect(savedTasks).not.toBeNull();
expect(savedTasks[1].sampleData.minute).toBe("2026-11-24 11:35");
expect(savedTasks[1].sampleData.timestampMs).toBe(1795093140000);
expect(choosesRefreshed).toBe(true);
});
});
+271 -7
View File
@@ -7,6 +7,9 @@ import {
editWorkflowTask,
removeWorkflowTask,
applyNodeMapping,
getJobExecutionTree,
listWorkflowLogs,
refreshWorkflowChooses,
} from "../../../domains/platform/workflow/services.js";
import { isServerManagedDescType } from "../../../domains/platform/workflow/nodes/mutations.js";
import { ValidationError } from "../../../core/errors.js";
@@ -26,7 +29,11 @@ async function saveNodeChanges(client: Parameters<typeof getWorkflowDetail>[0],
});
}
const SUB_ACTIONS = new Set(["list", "ls", "get", "show", "info", "add", "append", "insert", "edit", "update", "set", "map", "rm", "remove", "delete", "del"]);
const SUB_ACTIONS = new Set([
"list", "ls", "get", "show", "info", "add", "append", "insert",
"edit", "update", "set", "map", "rm", "remove", "delete", "del",
"inspect", "probe", "examine", "sample-save", "save-sample",
]);
export async function handleNodeCommand(
parsed: CliParsedArgs,
@@ -79,12 +86,14 @@ export async function handleNodeCommand(
"用法: hose-use workflow node <子命令> <pipelineId> [选项]",
"",
"子命令 (工作流级别):",
" list <pipelineId> 列出工作流所有任务节点 (别名: ls, 默认)",
" get <pipelineId> <节点标识> 查看指定节点的完整配置 (别名: show, info)",
" add <pipelineId> [选项] 声明式追加或插入新任务节点 (别名: append, insert)",
" edit <pipelineId> <节点标识> 定向修改指定节点配置 (别名: update, set)",
" map <pipelineId> <节点标识> 从映射文件批量更新深层字段 (别名: node map --mapping-file)",
" rm <pipelineId> <节点标识> 安全移除指定任务节点 (别名: remove, delete)",
" list <pipelineId> 列出工作流所有任务节点 (别名: ls, 默认)",
" get <pipelineId> <节点标识> 查看指定节点的完整配置 (别名: show, info)",
" inspect <pipelineId> <节点标识> 透视节点契约、样本与最近调试出参 (别名: probe)",
" sample-save <pipelineId> <节点标识> 固化指定 Job 或最新调测出参为 sampleData",
" add <pipelineId> [选项] 声明式追加或插入新任务节点 (别名: append, insert)",
" edit <pipelineId> <节点标识> 定向修改指定节点配置 (别名: update, set)",
" map <pipelineId> <节点标识> 从映射文件批量更新深层字段 (别名: node map --mapping-file)",
" rm <pipelineId> <节点标识> 安全移除指定任务节点 (别名: remove, delete)",
"",
"子命令 (企业灰度节点级别):",
" nodes [list] [--all] 列出当前企业已开通的节点字典 (别名: probe, catalog)",
@@ -107,6 +116,13 @@ export async function handleNodeCommand(
case "list":
case "ls":
return handleListNodes(pipelineId, parsed, runtime);
case "inspect":
case "probe":
case "examine":
return handleInspectNode(pipelineId, nodeTarget, parsed, runtime);
case "sample-save":
case "save-sample":
return handleSaveNodeSample(pipelineId, nodeTarget, parsed, runtime);
case "get":
case "show":
case "info":
@@ -677,3 +693,251 @@ async function handleRemoveNode(
exitCode: 0,
};
}
async function handleInspectNode(
pipelineId: string,
nodeTarget: string,
parsed: CliParsedArgs,
runtime: CliRuntime
): Promise<CliResult> {
if (!nodeTarget) {
return {
stdout: "",
stderr: "请提供节点标识 (name 或层级序号): hose-use workflow node inspect <pipelineId> <nodeNameOrIndex>\n",
exitCode: 1,
};
}
const { client, platformId } = await createWorkflowDetailClient(parsed, runtime, pipelineId);
const detail = await getWorkflowDetail(client, pipelineId);
const located = findWorkflowTask(detail.tasks || [], nodeTarget);
if (!located) {
return {
stdout: "",
stderr: `在工作流 [${pipelineId}] 中未找到节点: ${nodeTarget}\n`,
exitCode: 1,
};
}
const { task, hierarchicalIndex, path, parentName } = located;
const sampleData = (task as any).sampleData ?? null;
let executionProbe: {
jobId: string;
status: string;
executionTime?: number;
output?: any;
error?: any;
} | null = null;
const targetJobId = stringOption(parsed.options, ["job", "job-id", "jobId"]);
try {
let jobIdToProbe = targetJobId;
if (!jobIdToProbe) {
const logs = await listWorkflowLogs(client, pipelineId, { pageSize: 1 });
const firstItem = logs.items?.[0] || (logs as any).records?.[0];
if (firstItem && firstItem.id) {
jobIdToProbe = firstItem.id;
}
}
if (jobIdToProbe) {
const tree = await getJobExecutionTree(client, jobIdToProbe);
const matchExecution = tree.find((exec) => exec.name === task.name || exec.id === task.name);
if (matchExecution) {
executionProbe = {
jobId: jobIdToProbe,
status: matchExecution.status || "UNKNOWN",
executionTime: (matchExecution as any).durationTime ?? matchExecution.executionTime,
output: matchExecution.output,
error: matchExecution.error,
};
}
}
} catch {
// 探针容错
}
if (runtime.jsonMode) {
return {
stdout: printJson(
{
pipelineId,
node: located,
sampleData,
executionProbe,
},
runtime.outputOptions
),
stderr: "",
exitCode: 0,
};
}
const outLines: string[] = [
`====== 工作流节点只读探针 [${detail.label || pipelineId}] · ${task.displayName || task.label || task.name} ======`,
`节点标识 (name) : ${task.name}`,
`层级编号 (#) : ${hierarchicalIndex}`,
`节点类型 (type) : ${task.type}`,
`节点标题 (label) : ${task.label || "-"}`,
`节点显示名 (display): ${(task as any).displayName || "-"}`,
`父容器节点 : ${parentName || "顶级节点 (root)"}`,
`JSON 路径 : ${path}`,
];
if ((task as any).code !== undefined) {
outLines.push(`脚本代码行数 : ${(task as any).code.split("\n").length} 行`);
}
if ((task as any).url) {
outLines.push(`请求 URL : ${(task as any).url}`);
}
if ((task as any).specificationId) {
outLines.push(`单据模板 ID : ${JSON.stringify((task as any).specificationId)}`);
}
outLines.push("");
outLines.push("── 📦 节点固化样本数据 (sampleData) ──");
if (sampleData && typeof sampleData === "object" && Object.keys(sampleData).length > 0) {
const keys = Object.keys(sampleData);
outLines.push(`状态: ✅ 已固化样本 (${keys.length} 个字段)`);
outLines.push(printJson(sampleData, runtime.outputOptions));
} else {
outLines.push("状态: ⚪ 暂无样本数据 (设计器下拉菜单将无法自动解析其结构化变量)");
outLines.push("💡 提示: 可运行 hose-use workflow node sample-save <pipelineId> <nodeName> 固化最近调测出参");
}
outLines.push("");
outLines.push("── 🧪 最近一次调试执行出参 (Execution Output Probe) ──");
if (executionProbe) {
outLines.push(`来源 Job ID : ${executionProbe.jobId}`);
outLines.push(`执行状态 (status) : ${executionProbe.status}`);
outLines.push(`执行耗时 (ms) : ${executionProbe.executionTime ?? "-"}`);
if (executionProbe.output && typeof executionProbe.output === "object") {
outLines.push(`出参全貌 (output):`);
outLines.push(printJson(executionProbe.output, runtime.outputOptions));
} else {
outLines.push(`出参: ${JSON.stringify(executionProbe.output ?? null)}`);
}
} else {
outLines.push("未找到或无匹配的最近调试执行记录。");
}
return { stdout: `${outLines.join("\n")}\n`, stderr: "", exitCode: 0 };
}
async function handleSaveNodeSample(
pipelineId: string,
nodeTarget: string,
parsed: CliParsedArgs,
runtime: CliRuntime
): Promise<CliResult> {
if (!nodeTarget) {
return {
stdout: "",
stderr: "用法: hose-use workflow node sample-save <pipelineId> <nodeNameOrIndex> [--job=<jobId>]\n",
exitCode: 1,
};
}
const { client, platformId } = await createWorkflowDetailClient(parsed, runtime, pipelineId);
const detail = await getWorkflowDetail(client, pipelineId);
const located = findWorkflowTask(detail.tasks || [], nodeTarget);
if (!located) {
return {
stdout: "",
stderr: `在工作流 [${pipelineId}] 中未找到节点: ${nodeTarget}\n`,
exitCode: 1,
};
}
const { task } = located;
const targetJobId = stringOption(parsed.options, ["job", "job-id", "jobId"]);
let jobIdToProbe = targetJobId;
if (!jobIdToProbe) {
const logs = await listWorkflowLogs(client, pipelineId, { pageSize: 1 });
const firstItem = logs.items?.[0] || (logs as any).records?.[0];
if (firstItem && firstItem.id) {
jobIdToProbe = firstItem.id;
}
}
if (!jobIdToProbe) {
return {
stdout: "",
stderr: `未指定 Job ID 且未查询到工作流 [${pipelineId}] 的历史运行日志,无法提取样本数据。请先执行调试或通过 --job=<id> 指定。\n`,
exitCode: 1,
};
}
const tree = await getJobExecutionTree(client, jobIdToProbe);
const matchExecution = tree.find((exec) => exec.name === task.name || exec.id === task.name);
if (!matchExecution || matchExecution.output === undefined) {
return {
stdout: "",
stderr: `在 Job [${jobIdToProbe}] 中未找到节点 [${task.name}] 的有效执行出参 (output)。\n`,
exitCode: 1,
};
}
const samplePayload = matchExecution.output;
if (isDryRun(parsed, runtime)) {
return mutationPreview(parsed, runtime, "固化节点样本数据 (sampleData)", `${pipelineId}:${task.name}`, {
pipelineId,
nodeName: task.name,
jobId: jobIdToProbe,
samplePayload,
});
}
requireMutationConfirmation(
parsed,
runtime,
"固化节点样本数据 (sampleData)",
`hose-use workflow node sample-save ${pipelineId} ${nodeTarget} --job=${jobIdToProbe} --yes`
);
(task as any).sampleData = samplePayload;
const saveResult = await saveNodeChanges(client, detail, detail, platformId);
try {
await refreshWorkflowChooses(client, pipelineId);
} catch {}
const fieldCount = typeof samplePayload === "object" && samplePayload !== null ? Object.keys(samplePayload).length : 1;
if (runtime.jsonMode) {
return {
stdout: printJson(
{
success: true,
pipelineId,
nodeName: task.name,
jobId: jobIdToProbe,
fieldsSaved: fieldCount,
sampleData: samplePayload,
workflow: saveResult,
},
runtime.outputOptions
),
stderr: "",
exitCode: 0,
};
}
return {
stdout: [
`✨ 节点 [${task.name}] (${task.displayName || task.label || task.type}) 样本数据 (sampleData) 固化成功!`,
` • 来源 Job ID : ${jobIdToProbe}`,
` • 固化字段数 : ${fieldCount} 个属性`,
` • 设计器联动 : 已刷新选择器 (chooses) 树,下游节点现在可在下拉列表中直接点选其输出变量。`,
`📌 ${formatWorkflowVersion(saveResult)}`,
].join("\n") + "\n",
stderr: "",
exitCode: 0,
};
}
+54 -1
View File
@@ -6,6 +6,9 @@ import {
getWorkflowDetail,
getWorkflowSampleData,
runWorkflowDebugTest,
updateWorkflow,
refreshWorkflowChooses,
flattenWorkflowTaskTree,
type WorkflowTriggerCategory,
} from "../../../domains/platform/workflow/services.js";
import { stringOption, booleanOption, numberOption } from "../../parser.js";
@@ -46,6 +49,7 @@ export async function handleWorkflowTest(
" 4. 外部调用 (webhook): --body='{...}' 或 --file=<path.json> 传入事件请求体",
"",
"通用选项:",
" --save-sample 调试通过后自动将执行节点的真实出参保存为样本数据 (sampleData)",
" --timeout=<ms> 设置轮询超时时间 (默认 15000ms)",
" --auto-publish 是否自动发布测试快照 (默认 false)",
" --allow-prod 确认在正式生产环境 (env: prod) 下执行调试(--force 为兼容别名)",
@@ -59,6 +63,7 @@ export async function handleWorkflowTest(
}
const autoPublish = booleanOption(parsed.options, ["auto-publish", "autoPublish", "publish"]);
const saveSample = booleanOption(parsed.options, ["save-sample", "saveSample", "save-samples", "saveSamples"]);
const timeoutMs = numberOption(parsed.options, ["timeout", "timeout-ms", "timeoutMs"]) ?? 15000;
const rawBody = stringOption(parsed.options, ["body", "data", "payload"]);
const filePath = stringOption(parsed.options, ["file", "path"]);
@@ -109,7 +114,7 @@ export async function handleWorkflowTest(
});
if (blocked) return blocked;
if (flowCodeOrId || rawBody || filePath || isEmpty) confirmExecution();
const { client } = await createWorkflowDetailClient(parsed, runtime, pipelineId);
const { client, platformId } = await createWorkflowDetailClient(parsed, runtime, pipelineId);
// 1. 获取工作流详情与触发器元数据
const detail = await getWorkflowDetail(client, pipelineId).catch(() => {
@@ -414,9 +419,48 @@ export async function handleWorkflowTest(
autoPublish,
timeoutMs,
});
const savedSampleNodes: Array<{ name: string; label: string; fieldCount: number }> = [];
if (saveSample && execution.outcome === "completed" && execution.executionTree?.length > 0) {
try {
const latestDetail = await getWorkflowDetail(client, pipelineId);
const flattened = flattenWorkflowTaskTree(latestDetail.tasks || []);
let updatedCount = 0;
for (const execNode of execution.executionTree) {
if (!execNode.name || execNode.output === undefined || execNode.output === null) continue;
if (typeof execNode.output !== "object" || Object.keys(execNode.output).length === 0) continue;
const matched = flattened.find((f) => f.task.name === execNode.name);
if (matched) {
(matched.task as any).sampleData = execNode.output;
savedSampleNodes.push({
name: matched.task.name,
label: (matched.task as any).displayName || matched.task.label || matched.task.type,
fieldCount: Object.keys(execNode.output).length,
});
updatedCount++;
}
}
if (updatedCount > 0) {
await updateWorkflow(client, latestDetail, {
platformId,
expectedVersion: { version: latestDetail.version, tasksVersion: latestDetail.tasksVersion },
});
try {
await refreshWorkflowChooses(client, pipelineId);
} catch {}
}
} catch (sampleErr: any) {
warnings.push(`自动固化样本数据警告: ${sampleErr.message || String(sampleErr)}`);
}
}
const report = {
...execution,
productionEnabled: detail ? isEnabled : null,
savedSampleNodes: savedSampleNodes.length > 0 ? savedSampleNodes : undefined,
warnings,
...productionOverrideMeta(
parsed,
@@ -514,6 +558,15 @@ export async function handleWorkflowTest(
outLines.push(...formatCodeNodeSummariesCard(codeSummaries, report.jobId));
}
if (savedSampleNodes.length > 0) {
outLines.push("");
outLines.push("── ✨ 样本数据自动固化 (Sample Data Saved) ──");
outLines.push(`已自动将 ${savedSampleNodes.length} 个节点的真实调试出参固化为 sampleData 并刷新设计器选择树:`);
for (const sn of savedSampleNodes) {
outLines.push(` • [${sn.name}] (${sn.label}): 固化 ${sn.fieldCount} 个属性`);
}
}
if (category === "WEBHOOK" && report.outcome !== "completed") {
outLines.push("");
outLines.push("💡 [Webhook 流程调试提示]");
+3 -2
View File
@@ -149,8 +149,9 @@ export class CorpContext {
if (!corp) return false;
this.current = corp;
this.defaultCorpId = corp.id;
if (persist && this.stateful) {
saveGlobalConfig({ defaultCorpId: corp.id });
if (persist) {
this.stateful = true;
saveGlobalConfig({ defaultCorpId: corp.id, stateful: true });
}
return true;
}