fix: identify invalid workflow nodes and validate motion limits independently

This commit is contained in:
lixiaolong 2026-11-12 19:00:50 +08:00
parent 44653a2a43
commit a8daacbf6b
7 changed files with 154 additions and 55 deletions

View File

@ -15,6 +15,19 @@ export function armMotionParamLabel(action, name) {
if (name === 'jointVelocityLimits') return '各关节速度上限(rad/s,数组)'
return ''
}
// Velocity and acceleration have different dimensions and must be checked independently.
export function armMotionScalarError(action, param) {
if (param?.type === 'quote' || !['velocity', 'acceleration'].includes(param?.name)) return ''
const label = armMotionParamLabel(action, param.name)
if (!label) return ''
const raw = param.input
const value = Number(raw)
if (raw === '' || raw == null || typeof raw === 'boolean' || !Number.isFinite(value) || value <= 0)
return `${label}必须为大于0的有效数值`
if (Number.isFinite(param.min) && value < param.min) return `${label}不能小于${param.min}`
if (Number.isFinite(param.max) && value > param.max) return `${label}不能大于${param.max}`
return ''
}
export const withArmMotionUnits = (action, params = []) => {
const source = ['ARM_MOVE_TO_J', 'ARM_MOVE_TO_POINT'].includes(action) && !params.some(p => p.name === 'timeoutMs')
? [...params, {name:'timeoutMs',label:'等待超时(毫秒)',type:'input',componentType:'number',input:ARM_DEFAULT_WAIT_MS,min:100,max:21600000,step:1000,required:true,disabled:true}] : params

View File

@ -1,6 +1,6 @@
import test from 'node:test'
import assert from 'node:assert/strict'
import { armMotionParamLabel, withArmMotionUnits, armMotionUnitHint } from './armMotionUnits.mjs'
import { armMotionParamLabel, withArmMotionUnits, armMotionUnitHint, armMotionScalarError } from './armMotionUnits.mjs'
test('给历史机械臂参数补充单位时,位置数值、关节数组、上游引用保持原样', () => {
const params = [{name:'x',type:'input',input:0.123}, {name:'rx',type:'quote',quote:['start','input','rx'],quoteType:'input'}, {name:'frame',input:'BASE'}]
@ -33,3 +33,12 @@ test('机械臂SDK单位标注不影响底盘与旋转底座的单位选择', ()
assert.equal(withArmMotionUnits(action,[param])[0],param)
}
})
test('速度与加速度按各自数值范围校验,不比较不同单位的大小', () => {
assert.equal(armMotionScalarError('ARM_MOVE_TO_J', {name:'velocity',type:'input',input:0.5,max:5}), '')
assert.equal(armMotionScalarError('ARM_MOVE_TO_J', {name:'acceleration',type:'input',input:0.2,max:5}), '')
for (const input of ['', null, 0, -1, Infinity, NaN, true, 'abc'])
assert.match(armMotionScalarError('ARM_MOVE_TO_J', {name:'velocity',type:'input',input}), /速度.*大于0/)
assert.match(armMotionScalarError('ARM_MOVE_TO_J', {name:'acceleration',type:'input',input:6,max:5}), /不能大于5/)
assert.equal(armMotionScalarError('ARM_MOVE_TO_J', {name:'velocity',type:'quote',input:'',quote:['speed','output','vec']}), '')
})

View File

@ -0,0 +1,38 @@
export function validationMessages(...values) {
const messages = new Set()
const seen = new Set()
const visit = (value) => {
if (!value || seen.has(value) || messages.size >= 50) return
if (typeof value === 'string') {
if (value.trim()) messages.add(value.trim())
return
}
if (typeof value !== 'object') return
seen.add(value)
if (Array.isArray(value)) value.forEach(visit)
else if (typeof value.message === 'string') visit(value.message)
else Object.values(value).forEach(visit)
}
values.forEach(visit)
return [...messages]
}
export function nodeValidationIssues(nodes, errors) {
const byId = new Map(nodes.map(node => [node.id, node]))
const issues = new Map()
for (const error of errors) {
const id = error.nodeId || error.id || (error.global ? '__flow__' : '')
const node = byId.get(id)
if (!node && !error.global) continue
const previous = issues.get(id)
issues.set(id, {
id,
name: node?.properties?.name || node?.text?.value || (node?.type === 'start' ? '流程开始' : error.global ? '流程整体' : id),
messages: validationMessages(previous?.messages, error.messages, error.message)
})
}
return [...issues.values()].map(issue => ({
...issue,
messages: issue.messages.length ? issue.messages : ['参数未通过校验,请打开节点配置检查必填项及引用']
}))
}

View File

@ -28,7 +28,7 @@
componentIdentity.category
}}</span>
</div>
<component
<div ref="paramsContentRef"><component
:is="currentComponent"
ref="paramsComponentRef"
:data="props.data"
@ -37,12 +37,20 @@
@save-error="handleSaveError"
@cancel="emits('close')"
@extract-step="handleExtractStep"
/>
/></div>
<template v-if="lastSaveErrors.length" #footer>
<div class="flow-params-validation-footer">
<span>请修正参数,或返回画布检查其他问题。</span>
<el-button @click="emits('close')">返回画布查看问题</el-button>
</div>
</template>
</el-drawer>
</template>
<script setup>
import { ref, computed } from 'vue'
import { ref, computed, nextTick, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { validationMessages } from '@/cmvr/common/utils/flowValidationIssues.mjs'
import { emitter } from '@/cmvr/common/utils/eventBus'
import { getFlowNodeIdentity } from '../config'
@ -79,6 +87,9 @@ const props = defineProps({
const emits = defineEmits(['close', 'extract-step'])
const paramsComponentRef = ref(null)
const paramsContentRef = ref(null)
const lastSaveErrors = ref([])
watch(() => props.data?.id, () => { lastSaveErrors.value = [] })
const componentIdentity = computed(() => getFlowNodeIdentity(props.data))
/**
@ -139,6 +150,7 @@ defineExpose({ confirmSave })
* 处理 handleSaveSuccess 对应的数据或交互;作用范围仅限当前组件或模块。
*/
const handleSaveSuccess = () => {
lastSaveErrors.value = []
const previous = globalThis.lf.getGraphData()
const resources = finishNodeResourceEdit(previous, props.data.id)
if (resources.start) globalThis.lf.setProperties(resources.start.id, resources.start.properties)
@ -159,10 +171,14 @@ const handleSaveSuccess = () => {
/**
* 处理 handleSaveError 对应的数据或交互;作用范围仅限当前组件或模块。
*/
const handleSaveError = () => {
const handleSaveError = async (error) => {
await nextTick()
const messages = validationMessages(error,
[...(paramsContentRef.value?.querySelectorAll('.el-form-item__error') || [])].map(item => item.textContent))
lastSaveErrors.value = messages.length ? messages : ['参数未通过校验']
emitter.emit('setProperties', { id: props.data.id })
emitter.emit('throwAnError', { id: props.data.id, hasError: true, type: props.data.type })
emits('close')
emitter.emit('throwAnError', { id: props.data.id, hasError: true, type: props.data.type, messages })
ElMessage.warning(`「${props.data.properties?.name || componentIdentity.value.label}」:${messages[0] || '参数未通过校验,请检查必填项及引用'}`)
}
const handleExtractStep = (payload) => emits('extract-step', payload)
@ -173,6 +189,7 @@ const handleExtractStep = (payload) => emits('extract-step', payload)
<style lang="scss">
.flow-params-drawer {
.flow-params-validation-footer { display: flex; align-items: center; justify-content: space-between; gap: 12px; font-size: 12px; color: var(--el-text-color-secondary); }
.el-drawer__header {
min-height: 62px;
margin-bottom: 0 !important;

View File

@ -143,6 +143,8 @@ import { ElMessage } from 'element-plus'
import { getDeviceKindForAction, toDeviceOptions } from '@/cmvr/common/utils/robotDevice'
import { actionRequiresDevice } from '@/cmvr/common/utils/flowResources'
import { isWorkcellAction, validateWorkcellLiterals } from '@/cmvr/common/utils/scanMotorNodes.mjs'
import { armMotionScalarError } from '@/cmvr/common/utils/armMotionUnits.mjs'
import { validationMessages } from '@/cmvr/common/utils/flowValidationIssues.mjs'
import { withArmMotionUnits, armMotionUnitHint } from '@/cmvr/common/utils/armMotionUnits.mjs'
import ArmFrameSelect from './ArmFrameSelect.vue'
import { coordinateLabel, validateLinearCoordinate } from '@/cmvr/common/utils/armUserCoordinates.mjs'
@ -257,31 +259,32 @@ watch(
const validateAndSave = async () => {
let inputValid = true
let outputValid = true
const errors = []
if(isLinearArmAction(props.data.properties.action)&&formData.nodeParams.some(p=>['baseFrame','tcpFrame','userCoordinateName','userCoordinateRevision'].includes(p.name)&&p.type==='quote')) {
ElMessage.warning('坐标系不使用引用,请读取机械臂后下拉选择');emit('save-error');return
emit('save-error', '坐标系不使用引用,请读取机械臂后下拉选择');return
}
const deviceErrors = validateWorkcellLiterals(props.data.properties.action, formData.nodeParams)
if (deviceErrors.length) {
inputValid = false
ElMessage.warning(deviceErrors[0])
errors.push(...deviceErrors)
}
if (dynamicFormRef.value) {
await dynamicFormRef.value.validate((valid) => { if (!valid) inputValid = false })
await dynamicFormRef.value.validate((valid, fields) => { if (!valid) { inputValid = false; errors.push(...validationMessages(fields)) } })
}
if (outputFormRef.value) {
await outputFormRef.value.validate((valid) => { if (!valid) outputValid = false })
await outputFormRef.value.validate((valid, fields) => { if (!valid) { outputValid = false; errors.push(...validationMessages(fields)) } })
}
if (isRobotNode.value && !formData.executionTarget.roleKey) {
inputValid = false
ElMessage.warning('请选择执行机器人角色')
errors.push('请选择执行机器人角色')
} else if (isRobotNode.value
&& actionRequiresDevice(props.data.properties.action)
&& !formData.executionTarget.deviceSlotKey) {
inputValid = false
ElMessage.warning('请选择该节点使用的设备用途')
errors.push('请选择该节点使用的设备用途')
}
if(isLinearArmAction(props.data.properties.action)&&!formData.nodeParams.some(p=>['baseFrame','tcpFrame','userCoordinateName','userCoordinateRevision','coordinateRelativeTranslation','rx','ry','rz'].includes(p.name)&&p.type==='quote')){try{validateLinearCoordinate(Object.fromEntries(formData.nodeParams.filter(p=>p.type==='input').map(p=>[p.name,p.input])))}catch(e){inputValid=false;ElMessage.warning(e.message)}}
if(isLinearArmAction(props.data.properties.action)&&!formData.nodeParams.some(p=>['baseFrame','tcpFrame','userCoordinateName','userCoordinateRevision','coordinateRelativeTranslation','rx','ry','rz'].includes(p.name)&&p.type==='quote')){try{validateLinearCoordinate(Object.fromEntries(formData.nodeParams.filter(p=>p.type==='input').map(p=>[p.name,p.input])))}catch(e){inputValid=false;errors.push(e.message)}}
// 非机器人节点不应携带机器人执行目标,避免后端将空对象误判为无效角色引用。
const properties = {
...props.data.properties,
@ -293,7 +296,7 @@ const validateAndSave = async () => {
if (inputValid && outputValid) {
emit('save-success')
} else {
emit('save-error')
emit('save-error', errors)
}
}
@ -363,31 +366,12 @@ const testRule = (property) => {
]
}
if (property?.name === 'acceleration') {
if (['velocity', 'acceleration'].includes(property?.name)) {
return [
{ required: true, message: '请输入参数值', trigger: 'blur' },
{ validator: () => {
if (formData.nodeParams.find(param => param.name === 'velocity')?.type === 'quote') return Promise.resolve()
if (formData.nodeParams.find(param => param.name === 'acceleration')?.input > formData.nodeParams.find(param => param.name === 'velocity')?.input) {
return Promise.resolve()
} else {
return Promise.reject(new Error('加速度必须大于速度'))
}
}, trigger: 'change' }
]
}
if (property?.name === 'velocity') {
return [
{ required: true, message: '请输入参数值', trigger: 'blur' },
{ validator: () => {
if (formData.nodeParams.find(param => param.name === 'acceleration')?.type === 'quote') return Promise.resolve()
if (formData.nodeParams.find(param => param.name === 'acceleration')?.input > formData.nodeParams.find(param => param.name === 'velocity')?.input) {
return Promise.resolve()
} else {
return Promise.reject(new Error('加速度必须大于速度'))
}
{ validator: (_rule, value) => {
const message = armMotionScalarError(props.data.properties.action, { ...property, input: value })
return message ? Promise.reject(new Error(message)) : Promise.resolve()
}, trigger: 'change' }
]

View File

@ -400,7 +400,11 @@ const validateAndSave = async () => {
})
if (hasErrors()) {
emit('save-error')
const model = editorInstance.getModel()
const errors = monaco.editor.getModelMarkers({ resource: model.uri })
.filter(marker => marker.severity === monaco.MarkerSeverity.Error)
.map(marker => `代码第${marker.startLineNumber}行:${marker.message}`)
emit('save-error', errors)
return
}

View File

@ -111,6 +111,16 @@
</el-header>
<el-alert v-if="controlAction === 'stop'" title="终止中,正在等待设备停止并确认资源释放,请勿重复操作。" type="info" :closable="false" show-icon />
<el-alert v-else-if="controlError" :title="controlError" type="warning" :closable="false" show-icon />
<section v-if="validationIssues.length" class="flow-validation" aria-label="流程校验问题">
<strong>校验未通过:{{ validationIssues.length }} 个节点需要检查</strong>
<div class="flow-validation__list">
<div v-for="issue in validationIssues" :key="issue.id" class="flow-validation__issue">
<el-button v-if="issue.id !== '__flow__'" link type="danger" @click="inspectValidationNode(issue.id)">{{ issue.name }} · {{ issue.id.slice(0, 8) }}</el-button>
<strong v-else>{{ issue.name }}</strong>
<span>{{ issue.messages.join(';') }}</span>
</div>
</div>
</section>
<el-container class="flow-workspace">
<el-aside v-if="!flowStore.disableForm && paletteVisible" class="flow-palette">
<Aside :flowId="flowInfoData.itemId" />
@ -380,6 +390,7 @@ const ActionQueueSingleRun = defineAsyncComponent(() => import("./components/Act
import { ElMessage, ElMessageBox } from "element-plus";
import { useFlowStore } from "@/cmvr/common/store/modules/flow";
import { emitter } from "@/cmvr/common/utils/eventBus";
import { validationMessages, nodeValidationIssues as describeNodeValidationIssues } from '@/cmvr/common/utils/flowValidationIssues.mjs';
import { convertToTree } from "@/cmvr/common/utils/flow";
import {
actionRequiresDevice,
@ -951,23 +962,18 @@ const testRun = async () => {
return !item.properties?.parentId && item.type !== "selectArea";
});
if (gl && gl.length > 0) {
ElMessage.warning("存在孤立的节点,请检查!");
return;
}
if (nodeErrorList.value.length > 0) {
ElMessage.warning("存在参数错误的节点,请检查!");
return;
}
const resourceValidation = validateFlowResources({ nodes, edges });
if (resourceValidation.errors.length > 0) {
const error = resourceValidation.errors[0];
ElMessage.warning(error.message);
if (error.nodeId) {
lf.selectElementById(error.nodeId);
lf.focusOn({ id: error.nodeId });
preflightIssues.value = [
...gl.map(node => ({ nodeId: node.id, message: '节点没有连线,请接入流程后再试运行' })),
...resourceValidation.errors.map(error => ({ ...error, global: !error.nodeId, nodeId: error.nodeId || nodes.find(node => node.type === 'start')?.id }))
];
if (validationIssues.value.length) {
const first = validationIssues.value[0];
ElMessage.warning(`「${first.name}」:${first.messages[0]}(共${validationIssues.value.length}个节点,点击问题列表可定位)`);
if (nodes.some(node => node.id === first.id)) {
lf.clearSelectElements();
lf.selectElementById(first.id);
lf.focusOn({ id: first.id });
}
return;
}
@ -2782,6 +2788,21 @@ const handleKeyboardShortcut = (event) => {
};
const nodeErrorList = ref([]);
const nodeErrorMessages = ref({});
const preflightIssues = ref([]);
const validationIssues = computed(() => describeNodeValidationIssues(lf.getGraphData().nodes || [], [
...preflightIssues.value,
...nodeErrorList.value.map(id => ({ id, messages: nodeErrorMessages.value[id] }))
]));
const inspectValidationNode = (id) => {
const node = lf.getGraphData().nodes.find(item => item.id === id);
if (!node) return;
lf.clearSelectElements();
lf.selectElementById(id);
lf.focusOn({ id });
paramsDrawerData.value = node;
showParamsDrawer.value = true;
};
onMounted(() => {
justLoadFlow();
@ -2817,12 +2838,14 @@ onMounted(() => {
}
}
if (hasError) {
nodeErrorMessages.value = { ...nodeErrorMessages.value, [id]: validationMessages(data.messages, data.message) };
if (!nodeErrorList.value.includes(id)) {
nodeErrorList.value.push(id);
if (element) element.style.background = "#ff00001a";
}
} else {
nodeErrorList.value = nodeErrorList.value.filter((item) => item !== id);
preflightIssues.value = preflightIssues.value.filter(item => item.nodeId !== id && item.id !== id);
if (element) element.style.background = "";
}
});
@ -3233,6 +3256,17 @@ onUnmounted(() => {
}
.version-history__meta,
.flow-validation {
flex-shrink: 0;
padding: 10px 16px;
border-bottom: 1px solid var(--el-color-danger-light-7);
background: var(--el-color-danger-light-9);
color: var(--el-text-color-primary);
font-size: 13px;
}
.flow-validation__list { max-height: 150px; overflow: auto; margin-top: 4px; }
.flow-validation__issue { display: flex; align-items: baseline; gap: 12px; padding: 3px 0; }
.flow-validation__issue > span { overflow-wrap: anywhere; }
.version-history__note {
margin-top: 6px;
color: var(--el-text-color-regular);