Repository navigation
fix: refresh and validate workflow node references - #8219
Conversation
| validator: (_rule, reference: string[]) => (getNodeReferenceError(model, reference) ? new Error(message) : true), | ||
| }, | ||
| ] | ||
| } |
There was a problem hiding this comment.
The code has no syntax errors, but there are several runtime-safety and maintainability issues.
Potential issues
-
referencemay beundefinedor not an arrayif (reference.length === 0) ...
This will throw if the form value is
undefined,null, or a non-array during initial render/validation. Guard withArray.isArray(reference). -
The custom validator duplicates the “required” rule
The first rule already handles required/empty array. The custom validator still runs and may throw on empty/undefined values. It should either safely returntruewhen the required rule is responsible, or handle all cases itself. -
getRequiredReferenceRulesdoes not acceptglobal
getNodeReferenceErrorsupports aglobalflag, butgetRequiredReferenceRulesalways validates withglobal = false. If this rule is used for global-only references, it may accept references it should reject. -
getNodeReferenceErrorreturns i18n keys, not actual messages
It returns'requiredMessage','invalidMessage','missingMessage', butgetRequiredReferenceRulesignores the specific key and always usescommon.validation.selectRequired. Either use the specific messages or simplify the helper to return a boolean. -
toRaw(model)may bypass Vue reactivity
IfgetNodeReferenceOptionsis used inside acomputedor render dependency,toRawprevents Vue from tracking changes to the model. Only usetoRawif you intentionally want an untracked read. -
Filter predicate does not return a boolean
children?.length && (...)
It can return
0,undefined, or a boolean. It works becausefiltercoerces values, but it is irregular. UseBoolean(children?.length). -
Hard-coded values and unclear boolean flags
['global', 'chat', 'output', 'loop']should be a named constant/Set.getUpNodeFieldList(false, false)is unclear; consider an options object or named constants.globalshadows the Node.js global name; considerglobalOnlyorincludeGlobalSources.
-
No explicit return types
getNodeReferenceErrorimplicitly returnsstring | undefined; define a union type such as'requiredMessage' | 'invalidMessage' | 'missingMessage' | undefined.
Suggested revised version
import { toRaw } from 'vue'
import type { WorkflowNodeModel } from '@/workflow-canvas/core/workflow-node'
import type { FormItemRule } from 'element-plus'
import { t } from '@/locales'
const GLOBAL_REFERENCE_GROUPS = new Set(['global', 'chat', 'output', 'loop'])
type NodeReferenceError =
| 'requiredMessage'
| 'invalidMessage'
| 'missingMessage'
| undefined
export function getNodeReferenceOptions(
model: WorkflowNodeModel,
global = false,
) {
const fieldGroups = toRaw(model).getUpNodeFieldList(false, false)
return fieldGroups.filter(
({ value, children }) =>
Boolean(children?.length) &&
(!global || GLOBAL_REFERENCE_GROUPS.has(value)),
)
}
export function getNodeReferenceError(
model: WorkflowNodeModel,
reference: unknown,
global = false,
): NodeReferenceError {
if (!Array.isArray(reference) || reference.length === 0) {
return 'requiredMessage'
}
if (reference.length < 2) {
return 'invalidMessage'
}
const [nodeId, fieldValue] = reference
const fieldGroup = getNodeReferenceOptions(model, global).find(
({ value }) => value === nodeId,
)
if (!fieldGroup?.children?.some(({ value }) => value === fieldValue)) {
return 'missingMessage'
}
return undefined
}
export function getRequiredReferenceRules(
model: WorkflowNodeModel,
global = false,
): FormItemRule[] {
const message = t('common.validation.selectRequired')
const trigger = ['change', 'blur']
return [
{
type: 'array',
required: true,
message,
trigger,
},
{
trigger,
validator: (_rule, reference: unknown) => {
// Let the first rule handle required/type errors.
if (!Array.isArray(reference) || reference.length === 0) {
return true
}
return getNodeReferenceError(model, reference, global)
? new Error(message)
: true
},
},
]
}Optimization suggestions
- If
getNodeReferenceOptionsis called frequently, cache the field groups per model revision or create afindNodeReferenceGrouphelper. - If locale changes dynamically,
t(...)is evaluated only when the rules are created. Rebuild the rules on locale change or use a computed rule factory. - If references can contain more than two path segments, validate the full path instead of only
[nodeId, fieldValue].
| <NodeCascader v-model="formData.document_list" :node-model="model" :placeholder="t('workflow.document.placeholder')" /> | ||
| </el-form-item> | ||
| </el-form> | ||
| </div> |
There was a problem hiding this comment.
The diff looks reasonable overall, but there are several things to verify:
-
Unused template ref / imports
- Removing
ref="documentCascaderRef"likely leavesdocumentCascaderRefunused. - Also check whether
useTemplateRefis still needed elsewhere. - If
documentCascaderRefwas used forvalidate(),clear(),focus(), etc., removing the ref will break that behavior. - If unused, remove the declaration and import to avoid lint/TS errors like
noUnusedLocals.
- Removing
-
Rules are recreated on every render
:rules="getRequiredReferenceRules(model)"
This calls the function during every render and may create new rule objects/arrays. Element Plus may treat that as a rules change, causing unnecessary watcher/validation churn. Prefer:
const documentListRules = computed(() => getRequiredReferenceRules(model))
<el-form-item ... :rules="documentListRules">
If
getRequiredReferenceRulesusesuseI18nor other composables internally, do not call it from the template/computed getter; refactor it to accepttor call it insetup. -
Verify rule parity
ConfirmgetRequiredReferenceRules(model)returns equivalent behavior to the old inline rule:type: 'array'required: true- localized message, ideally
t('workflow.document.requiredMessage') trigger: 'change'
Otherwise validation timing or the user-facing message may regress.
-
Check
modelcorrectness and reactivity- Ensure
modelis the expected argument forgetRequiredReferenceRules. - If
modelcan beundefinedor is not reactive, the rules may be stale or throw. - If the rules depend on nested reactive fields, make sure the computed/render access tracks them correctly.
- Ensure
-
Import path
- Verify
@/workflow-canvas/component/node-cascader/index.vueexists with the exact casing. Case-sensitive filesystems will fail if the directory/file name differs. - Prefer a barrel import such as
@/workflow-canvas/component/node-cascaderif the project exposes one. - Check that no other files still import the old
NodeCascader.vuepath.
- Verify
-
Possible circular dependency
- Confirm
node-referencedoes not import the component or other UI code that importsnode-reference, which could create a circular dependency.
- Confirm
-
Formatting/lint
- The new
NodeCascaderline is long; run the project formatter. - Check for unused imports such as
computedorinjectif this diff changed their usage.
- The new
Main actionable fix: remove the now-unused template ref/import if it is no longer needed, and move getRequiredReferenceRules(model) into a computed property rather than calling it directly in the template.
| <NodeCascader v-model="formData.image_list" :node-model="model" :placeholder="t('common.placeholders.select')" /> | ||
| </el-form-item> | ||
|
|
||
| <!-- 输出思考 --> |
There was a problem hiding this comment.
Review of the diff
1. High priority — possible breakage
a) Removed ref="imageCascaderRef" may leave dangling code
The ref was presumably used somewhere in the script (const imageCascaderRef = ref(...), a manual validate() call, an exposed method, or a test). After removing it:
- The declaration in
<script setup>becomes an unused variable → ESLint error / dead code. - Any usage (
imageCascaderRef.value?.something, tests querying it) silently breaks. refmay also become an unused import.
Verify with:
grep -rn "imageCascaderRef" . # src + tests
If it was only needed for validation, formRef.value?.validate() already covers it — but confirm.
b) Rules object is rebuilt on every render
:rules="getRequiredReferenceRules(model)"Element Plus el-form-item watches the rules prop; a new array/object identity each render causes the watcher to re-fire and can trigger repeated/extra validation (and in some setups a validate loop). Prefer a stable, cached reference:
const imageListRules = computed(() => getRequiredReferenceRules(model))<el-form-item class="mk-hide-asterisk" prop="image_list" :rules="imageListRules">This keeps reactivity (recomputed when model changes) without churn. (The old inline literal had the same identity‑churn issue, so this is a good moment to fix it.)
c) Verify the helper preserves semantics
getRequiredReferenceRules must return rules equivalent to the removed literal:
required: true— otherwise the field is no longer enforced as required (themk-requiredspan is only visual; themk-hide-asteriskclass only hides the asterisk).- the same
t('common.validation.selectRequired')message key — otherwise the user-visible text changes. trigger: 'change'(or a superset) — otherwise validation timing changes.- a
validatorwhose field reference matchesprop="image_list". If the validator validates a hard‑coded field name, binding it toimage_listmay validate nothing. - no
useI18n()call at module/render scope insidenode-reference; if it relies on injection it can warn/fail when invoked during template render. Globali18n.global.tis fine.
d) Custom component + form validation trigger (pre-existing, worth checking)
el-form-item trigger‑based validation only works if the child calls formItemContext.validate('change') (e.g. via useFormItem). A custom NodeCascader won't emit Element Plus' internal validate event. If it doesn't dispatch validation itself, trigger: 'change' never fires and the field is only validated on submit. Consider having NodeCascader call formItem.validate('change') on update:modelValue, or add 'blur'/explicit validation.
2. Medium
a) Deep import into a component's internals
import { getRequiredReferenceRules } from '@/workflow-canvas/component/node-cascader/node-reference'This bypasses the folder's public surface. Prefer exporting it from the folder barrel:
// node-cascader/index.ts
export { getRequiredReferenceRules } from './node-reference'then import { getRequiredReferenceRules } from '@/workflow-canvas/component/node-cascader'. This also avoids breaking every consumer if the internal file moves/renames. If it's genuinely shared logic, move it to workflow-canvas/utils or composables/.
b) Path style inconsistency
.../node-cascader/index.vue is explicit; if the alias/build resolves directories, @/workflow-canvas/component/node-cascader is cleaner and stays valid if the entry later becomes index.ts. Also confirm the refactor didn't change NodeCascader's props/emits/default export name.
c) Argument type
Confirm getRequiredReferenceRules expects WorkflowNodeModel (and not model.data, model.refs, or a ModelItem). If it's loosely typed (any), a wrong argument will compile but validate the wrong thing.
d) Incomplete refactor
Other reference fields in this file (file_list, video_list, audio_list, any other NodeCascader) probably still use the inline required rule. If the helper adds reference‑existence checks, those fields now behave inconsistently — apply it uniformly.
e) Circular dependency risk
node-reference living inside the component folder may import constants/config that import the component barrel. Check the bundle for cycles (madge --circular), especially after switching the import path.
3. Low / style
- Import ordering:
node-cascader/node-referenceinserted betweenThinkingSettingandNodeModelSelectbreaks the existing grouping; run ESLintimport/order(or sort by path depth/case consistently). - Keep the
<!-- 选择图片 -->comment — unchanged, good. - If
getRequiredReferenceRulesallocates arrays, make sure it doesn't mutatemodelor shared constants. - Add a brief JSDoc on the helper stating which
propname it targets.
Suggested patch
-import NodeCascader from '@/workflow-canvas/component/node-cascader/index.vue'
-import { getRequiredReferenceRules } from '@/workflow-canvas/component/node-cascader/node-reference'
+import NodeCascader, { getRequiredReferenceRules } from '@/workflow-canvas/component/node-cascader'
+const imageListRules = computed(() => getRequiredReferenceRules(model))- <el-form-item class="mk-hide-asterisk" prop="image_list" :rules="getRequiredReferenceRules(model)">
+ <el-form-item class="mk-hide-asterisk" prop="image_list" :rules="imageListRules">
...
- <NodeCascader v-model="formData.image_list" :node-model="model" :placeholder="t('common.placeholders.select')" />
+ <NodeCascader
+ v-model="formData.image_list"
+ :node-model="model"
+ :placeholder="t('common.placeholders.select')"
+ @update:model-value="formRef?.validateField('image_list')"
+ />(the validator call is only needed if NodeCascader doesn't already integrate with el-form-item — otherwise drop it.)
Checklist before merging
grepforimageCascaderRefand remove the leftover declaration / fix tests.- Confirm
getRequiredReferenceRulesreturnsrequired: true, the same i18n key, and the same trigger. - Cache the rules with
computed. - Decide on barrel export vs deep import.
- Confirm no circular import and that
NodeCascader's public API is unchanged. - Apply the same helper to the other reference fields for consistency.
fix: refresh and validate workflow node references