feat(workflow): 支持节点 displayName 并限制 20 字标题

- 新增 --display-name,写入设计器真正持久化的节点标题 displayName;--label 保留为节点类型标题
- 新增/编辑/映射节点统一校验节点标题不超过 20 个 Unicode 字符,超出时本地直接拒绝
- 节点列表与详情优先展示 displayName,并在使用 --label 时提示服务端可能重新生成
- 记录后端不限制长度、仅前端设计器限制 20 字的验证结论
- 补充节点变更单测与 CLI 共享 flag 词表
This commit is contained in:
gitea committed 2026-10-28 10:55:56 +08:00
1 parent 96f4148f67
commit 1a2e485caa
6 files changed
+453 -366

No files matched your search

+354 -352
View File
File diff suppressed because it is too large. Load diff
+1 -1
View File
@@ -272,7 +272,7 @@ export const COMMAND_METADATA: Record<string, CliCommandMetadata> = {
"dictionary": "enum",
"dict": "enum"
},
flags: { ...flagList("all allow-prod allow-production auto-publish autoPublish compare detail diff empty errors f fail fail-on-alert failOnAlert failed failed-only failedOnly follow force force-write forceWrite full has-error hasError in-place inPlace includeDetail 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 code code-file container count d data desc description end-time endTime entity execution-logs field file filter flow flow-code flowCode from i id input input-file insert-after interval job job-id job1 job2 jobA jobB jobId json-file keyword l label limit log logs mapping mapping-file max-jobs maxJobs n name node node-id nodeId nodes output output-file outputFile p page page-size pageSize parent parent-id parentId password path payload pipeline pipeline-id pipelineId platform platform-id platformId pwd q query record s sample sample-id sampleId set size snapshot1 snapshot2 snapshotA snapshotB source start-time startTime state state-file stateFile t target targetName targetPlatformId task taskType third-id thirdId timeout timeout-ms timeoutMs to trigger type types value workflowId", "value") }
flags: { ...flagList("all allow-prod allow-production auto-publish autoPublish compare detail diff empty errors f fail fail-on-alert failOnAlert failed failed-only failedOnly follow force force-write forceWrite full has-error hasError in-place inPlace includeDetail 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 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 n name node node-id nodeId nodes output output-file outputFile p page page-size pageSize parent parent-id parentId password path payload pipeline pipeline-id pipelineId platform platform-id platformId pwd q query record s sample sample-id sampleId set size snapshot1 snapshot2 snapshotA snapshotB source start-time startTime state state-file stateFile t target targetName targetPlatformId task taskType third-id thirdId timeout timeout-ms timeoutMs to trigger type types value workflowId", "value") }
},
"bill": {
"summary": "单据检索、表单规格诊断与审批动作",
+22 -9
View File
@@ -158,13 +158,13 @@ async function handleListNodes(
item.hierarchicalIndex,
item.task.name,
item.task.type,
item.task.label || "-",
item.task.displayName || item.task.label || "-",
item.task.groupName || "-",
item.summary,
]);
const table = printTable(
["#", "节点标识 (name)", "类型 (type)", "标题 (label)", "分组", "配置摘要"],
["#", "节点标识 (name)", "类型 (type)", "标题", "分组", "配置摘要"],
rows
);
@@ -219,6 +219,7 @@ async function handleGetNode(
"父容器节点": parentName || "顶级节点 (root)",
"节点类型 (type)": task.type,
"节点标题 (label)": task.label || "-",
"节点显示名 (displayName)": (task as any).displayName || "-",
"节点分组 (group)": task.groupName || "-",
"状态 (status)": task.status || "active",
};
@@ -228,7 +229,7 @@ async function handleGetNode(
}
const outLines = [
`====== 节点详情 [${task.name}] (${task.label || task.type}) ======`,
`====== 节点详情 [${task.name}] (${(task as any).displayName || task.label || task.type}) ======`,
printKeyValue(kv),
];
@@ -255,7 +256,8 @@ async function handleAddNode(
"",
"常用选项:",
" --type=<type> 节点类型 (如 code-js2 / code)",
" --label=<标题> 节点显示名称",
" --label=<标题> 节点类型标题",
" --display-name=<名称> 设计器节点标题(displayName,最多 20 字符)",
" --code-file=<脚本路径> (推荐) 从本地文件导入代码,避免终端转义与 Token 浪费",
" --code=<代码片段> 传入代码字符串(仅限简短代码)",
" --parent=<容器节点name> 插入指定容器节点内部 (如 every 循环)",
@@ -269,6 +271,7 @@ async function handleAddNode(
}
const label = stringOption(parsed.options, ["label", "name", "l"]);
const displayName = stringOption(parsed.options, ["display-name", "displayName", "display"]);
const parent = stringOption(parsed.options, ["parent", "container", "p"]);
const after = stringOption(parsed.options, ["after", "insert-after"]);
const desc = stringOption(parsed.options, ["desc", "description", "d"]);
@@ -284,7 +287,7 @@ async function handleAddNode(
parsed,
runtime,
"追加工作流节点",
`hose-use workflow node add ${pipelineId} --type=${type}${label ? ` --label="${label}"` : ""}${parent ? ` --parent="${parent}"` : ""}${after ? ` --after="${after}"` : ""} --yes`
`hose-use workflow node add ${pipelineId} --type=${type}${label ? ` --label="${label}"` : ""}${displayName ? ` --display-name="${displayName}"` : ""}${parent ? ` --parent="${parent}"` : ""}${after ? ` --after="${after}"` : ""} --yes`
);
const { client } = await createWorkflowDetailClient(parsed, runtime, pipelineId);
@@ -293,6 +296,7 @@ async function handleAddNode(
const { workflow: updatedWorkflow, newTask } = addWorkflowTask(detail, {
type,
label,
displayName,
desc,
code,
parent,
@@ -305,6 +309,7 @@ async function handleAddNode(
newNodeName: newTask.name,
type: newTask.type,
label: newTask.label,
displayName: newTask.displayName,
targetLocation: parent ? `容器 [${parent}] 内部` : after ? `节点 [${after}] 之后` : "工作流末尾",
totalTasksCount: updatedWorkflow.tasks?.length || 0,
});
@@ -321,11 +326,12 @@ async function handleAddNode(
}
const out = [
`✨ 节点 [${newTask.name}] (${newTask.label}) 已成功添加至工作流 [${pipelineId}]:`,
`✨ 节点 [${newTask.name}] (${newTask.displayName || newTask.label}) 已成功添加至工作流 [${pipelineId}]:`,
printKeyValue({
"节点标识 (name)": newTask.name,
"节点类型 (type)": newTask.type,
"节点标题 (label)": newTask.label || "-",
"节点显示名 (displayName)": newTask.displayName || "-",
"所属位置": parent ? `容器 [${parent}] 内部` : after ? `节点 [${after}] 之后` : "工作流顶级末尾",
"节点总数": String(saveResult.tasks?.length || updatedWorkflow.tasks?.length || 0),
}),
@@ -347,7 +353,8 @@ async function handleEditNode(
"请提供节点标识 (name 或层级序号): hose-use workflow node edit <pipelineId> <nodeNameOrIndex> [选项]",
"",
"常用选项:",
" --label=<新名称> 更新节点显示标题",
" --label=<类型标题> 更新节点类型标题(服务端保存时可能重新生成)",
" --display-name=<新名称> 更新设计器节点标题(displayName,最多 20 字符)",
" --code-file=<脚本路径> (推荐) 从本地文件导入最新脚本,避免终端转义与 Token 浪费",
" --code=<行内代码> 直接传入代码片段(短脚本)",
" --desc=<描述> 更新节点描述",
@@ -363,6 +370,7 @@ async function handleEditNode(
}
const label = stringOption(parsed.options, ["label", "l"]);
const displayName = stringOption(parsed.options, ["display-name", "displayName", "display"]);
const desc = stringOption(parsed.options, ["desc", "description", "d"]);
const codeFile = stringOption(parsed.options, ["code-file", "file"]);
let code = stringOption(parsed.options, ["code", "c"]);
@@ -399,7 +407,7 @@ async function handleEditNode(
parsed,
runtime,
"修改工作流节点",
`hose-use workflow node edit ${pipelineId} ${nodeTarget}${label ? ` --label="${label}"` : ""} --yes`
`hose-use workflow node edit ${pipelineId} ${nodeTarget}${label ? ` --label="${label}"` : ""}${displayName ? ` --display-name="${displayName}"` : ""} --yes`
);
const { client } = await createWorkflowDetailClient(parsed, runtime, pipelineId);
@@ -407,6 +415,7 @@ async function handleEditNode(
const { workflow: updatedWorkflow, editedTask } = editWorkflowTask(detail, nodeTarget, {
label,
displayName,
desc,
code,
set: Object.keys(customSet).length > 0 ? customSet : undefined,
@@ -419,6 +428,7 @@ async function handleEditNode(
label: editedTask.label,
updatedFields: {
...(label ? { label } : {}),
...(displayName !== undefined ? { displayName } : {}),
...(desc ? { desc } : {}),
...(code !== undefined ? { code: `${code.length} 字符${!codeFile && code.length > 300 ? " [TIP: 建议使用 --code-file=<path> 从本地文件载入以规避转义错误并节省 Token]" : ""}` } : {}),
...customSet,
@@ -440,9 +450,12 @@ async function handleEditNode(
if (!codeFile && code && code.length > 300) {
codeTip = `\n💡 提示: 检测到通过命令行行内传入大段代码 (${code.length} 字符)。建议将脚本落地为本地文件并通过 --code-file=<路径> 传入,避免 Token 浪费与 Shell 转义风险。\n`;
}
const labelTip = label
? "\n💡 提示: --label 是节点类型标题,服务端保存时可能重新生成;要修改设计器标题请使用 --display-name。\n"
: "";
return {
stdout: `✅ 节点 [${editedTask.name}] (${editedTask.label}) 修改已保存至工作流 [${pipelineId}]。\n${codeTip}`,
stdout: `✅ 节点 [${editedTask.name}] (${editedTask.displayName || editedTask.label}) 修改已保存至工作流 [${pipelineId}]。\n${codeTip}${labelTip}`,
stderr: "",
exitCode: 0,
};
@@ -23,8 +23,8 @@ hose-use workflow nodes [list] [--all]
hose-use workflow nodes grant <type...> [--password=<pwd>] [--dry-run|--yes]
hose-use workflow node list <pipelineId>
hose-use workflow node get <pipelineId> <节点name或#序号>
hose-use workflow node add <pipelineId> --type=code-js2 --label="清洗" --code="..." [--after=<节点>] [--parent=<容器>] [--dry-run|--yes]
hose-use workflow node edit <pipelineId> <节点name或#序号> --label="新标题" [--code="..."] [--dry-run|--yes]
hose-use workflow node add <pipelineId> --type=code-js2 --label="清洗" --display-name="清洗节点" --code="..." [--after=<节点>] [--parent=<容器>] [--dry-run|--yes]
hose-use workflow node edit <pipelineId> <节点name或#序号> --display-name="新标题" [--code="..."] [--dry-run|--yes]
hose-use workflow node rm <pipelineId> <节点name或#序号> [--dry-run|--yes]
hose-use workflow tail <pipelineId> [--job=<jobId>] [--once] [--failed-only] [--interval=2] [--json]
hose-use workflow lint-script <pipelineId> [节点标识] [--json]
@@ -145,6 +145,8 @@ MVEL 本地仿真支持的是转译子集:零参 `HashMap` / `ArrayList` 及 `
`node edit --file=<脚本>` 是 `--code-file` 的兼容别名;编辑字段映射使用 `--mapping-file=<JSON>`,或独立的 `node map --file=<JSON>`。不根据文件扩展名猜测用途。
节点卡片标题保存在 `displayName`,用 `--display-name` 修改;`--label` 是节点类型标题,服务端保存时可能按节点类型重新生成,不能可靠地用于重命名已有节点。设计器前端把节点标题限制为 20 个字符;后端本身不校验该长度(实测 21 字仍可保存),本地 CLI 按前端上限强制校验,超过 20 个 Unicode 字符会在写入前抛出 `ValidationError`。条件/内置节点类型的 `desc` 也由平台按配置重新生成,自定义 `--desc` 可能不会持久化。
灰度开通遵循统一写操作门禁:`--dry-run` 仅返回归一化节点清单且不调用网关;实际开通需要 `--yes/--confirm`。管理员密码用于额外授权,不能替代写操作确认。
节点定位约定:CLI 的字符串编号(如 `3`、`2.1`)始终对应列表展示的层级编号;SDK 传入数字 `3` 时表示深度优先遍历的第 3 个节点。节点名称仍可直接用于定位,两个编号体系不再在一次查找中竞争。
@@ -8,6 +8,9 @@ import {
removeWorkflowTask,
buildWorkflowTask,
summarizeTask,
MAX_NODE_DISPLAY_NAME_LENGTH,
displayNameLength,
isDisplayNameTooLong,
} from "./index.js";
import type { WorkflowDetail, WorkflowTask } from "../../types.js";
@@ -240,6 +243,27 @@ describe("workflow-nodes - 任务节点声明式编排纯函数", () => {
expect(mockWorkflow.tasks[1].tasks![0].label).toBe("数据清洗");
});
it("enforces the 20-character designer display name limit", () => {
expect(MAX_NODE_DISPLAY_NAME_LENGTH).toBe(20);
expect(displayNameLength("选核销单号")).toBe(5);
expect(isDisplayNameTooLong("一".repeat(20))).toBe(false);
expect(isDisplayNameTooLong("一".repeat(21))).toBe(true);
const built = buildWorkflowTask("code", { displayName: " 选核销单号 " });
expect((built as any).displayName).toBe("选核销单号");
const { newTask } = addWorkflowTask(mockWorkflow, { type: "code", displayName: "新节点" });
expect((newTask as any).displayName).toBe("新节点");
const { editedTask } = editWorkflowTask(mockWorkflow, "action_js_1", {
displayName: " 清洗节点 ",
});
expect((editedTask as any).displayName).toBe("清洗节点");
expect(() => buildWorkflowTask("code", { displayName: "一".repeat(21) })).toThrow("最多 20 个字符");
expect(() => editWorkflowTask(mockWorkflow, "action_js_1", { displayName: "一".repeat(21) })).toThrow("最多 20 个字符");
expect(() => editWorkflowTask(mockWorkflow, "action_js_1", { set: { displayName: "一".repeat(21) } })).toThrow("最多 20 个字符");
});
it("removeWorkflowTask safely removes task and guards trigger node", () => {
// 1. Remove child task in container
const { workflow: wfRemoved, removedTask } = removeWorkflowTask(mockWorkflow, "action_js_1");
@@ -36,9 +36,21 @@ export function generateNodeName(type: string): string {
return `action_${rand}`;
}
export const MAX_NODE_DISPLAY_NAME_LENGTH = 20;
/** 设计器节点标题按 Unicode 字符计数(中文与 emoji 均算 1 个字符)。 */
export function displayNameLength(name: string): number {
return Array.from(name.trim()).length;
}
export function isDisplayNameTooLong(name: string): boolean {
return displayNameLength(name) > MAX_NODE_DISPLAY_NAME_LENGTH;
}
export interface AddTaskOptions {
type: string;
label?: string;
displayName?: string;
code?: string;
desc?: string;
parent?: string | number;
@@ -49,7 +61,7 @@ export interface AddTaskOptions {
/**
* 构建规范的新节点对象
*/
export function buildWorkflowTask(type: string, options: Partial<AddTaskOptions> = {}): WorkflowTask {
function buildWorkflowTaskBase(type: string, options: Partial<AddTaskOptions> = {}): WorkflowTask {
const normType = type.trim();
const name = generateNodeName(normType);
@@ -205,6 +217,30 @@ export function buildWorkflowTask(type: string, options: Partial<AddTaskOptions>
}
}
function applyDisplayName(task: WorkflowTask, displayName?: string): void {
if (displayName === undefined) return;
const trimmed = displayName.trim();
if (!trimmed) {
delete (task as any).displayName;
return;
}
if (isDisplayNameTooLong(trimmed)) {
throw new ValidationError(
`节点显示名称最多 ${MAX_NODE_DISPLAY_NAME_LENGTH} 个字符(前端设计器上限),当前 ${displayNameLength(trimmed)} 个字符: ${trimmed}`
);
}
(task as any).displayName = trimmed;
}
/**
* 构建规范的新节点对象
*/
export function buildWorkflowTask(type: string, options: Partial<AddTaskOptions> = {}): WorkflowTask {
const task = buildWorkflowTaskBase(type, options);
applyDisplayName(task, options.displayName);
return task;
}
/**
* 向工作流声明式追加或插入任务节点
*/
@@ -243,6 +279,7 @@ export function addWorkflowTask(
export interface EditTaskOptions {
label?: string;
displayName?: string;
code?: string;
desc?: string;
set?: Record<string, any>;
@@ -266,11 +303,16 @@ export function editWorkflowTask(
const { task } = target;
if (updates.label !== undefined) task.label = updates.label;
if (updates.displayName !== undefined) applyDisplayName(task, updates.displayName);
if (updates.desc !== undefined) task.desc = updates.desc;
if (updates.code !== undefined) (task as any).code = updates.code;
if (updates.set && typeof updates.set === "object") {
for (const [k, v] of Object.entries(updates.set)) {
if (k === "displayName") {
applyDisplayName(task, typeof v === "string" ? v : v == null ? "" : String(v));
continue;
}
(task as any)[k] = v;
}
}
@@ -339,7 +381,11 @@ export function applyNodeMapping(
} else if (mapping && typeof mapping === "object") {
// 对象格式:合并/设置每个顶层键
for (const [key, value] of Object.entries(mapping)) {
(task as any)[key] = value;
if (key === "displayName") {
applyDisplayName(task, typeof value === "string" ? value : value == null ? "" : String(value));
} else {
(task as any)[key] = value;
}
if (Array.isArray(value)) {
changedKeys.push(`${key} (${value.length} 项)`);
} else {