Skip to content

fix: refresh and validate workflow node references - #8219

Merged
wangdan-fit2cloud merged 1 commit into
v3from
pr@v3@fix_cascader
Nov 30, 2026
Merged

wangdan-fit2cloud merged 1 commit into
v3from
pr@v3@fix_cascader

Conversation

@shaohuzhang1

Copy link
Copy Markdown
Contributor

fix: refresh and validate workflow node references

validator: (_rule, reference: string[]) => (getNodeReferenceError(model, reference) ? new Error(message) : true),
},
]
}

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The code has no syntax errors, but there are several runtime-safety and maintainability issues.

Potential issues

  1. reference may be undefined or not an array

    if (reference.length === 0) ...

    This will throw if the form value is undefined, null, or a non-array during initial render/validation. Guard with Array.isArray(reference).

  2. 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 return true when the required rule is responsible, or handle all cases itself.

  3. getRequiredReferenceRules does not accept global
    getNodeReferenceError supports a global flag, but getRequiredReferenceRules always validates with global = false. If this rule is used for global-only references, it may accept references it should reject.

  4. getNodeReferenceError returns i18n keys, not actual messages
    It returns 'requiredMessage', 'invalidMessage', 'missingMessage', but getRequiredReferenceRules ignores the specific key and always uses common.validation.selectRequired. Either use the specific messages or simplify the helper to return a boolean.

  5. toRaw(model) may bypass Vue reactivity
    If getNodeReferenceOptions is used inside a computed or render dependency, toRaw prevents Vue from tracking changes to the model. Only use toRaw if you intentionally want an untracked read.

  6. Filter predicate does not return a boolean

    children?.length && (...)

    It can return 0, undefined, or a boolean. It works because filter coerces values, but it is irregular. Use Boolean(children?.length).

  7. 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.
    • global shadows the Node.js global name; consider globalOnly or includeGlobalSources.
  8. No explicit return types
    getNodeReferenceError implicitly returns string | 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 getNodeReferenceOptions is called frequently, cache the field groups per model revision or create a findNodeReferenceGroup helper.
  • 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].

@wangdan-fit2cloud
wangdan-fit2cloud merged commit d84c06e into v3 Nov 30, 2026
3 of 4 checks passed
@wangdan-fit2cloud
wangdan-fit2cloud deleted the pr@v3@fix_cascader branch November 30, 2026 07:41
<NodeCascader v-model="formData.document_list" :node-model="model" :placeholder="t('workflow.document.placeholder')" />
</el-form-item>
</el-form>
</div>

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The diff looks reasonable overall, but there are several things to verify:

  1. Unused template ref / imports

    • Removing ref="documentCascaderRef" likely leaves documentCascaderRef unused.
    • Also check whether useTemplateRef is still needed elsewhere.
    • If documentCascaderRef was used for validate(), clear(), focus(), etc., removing the ref will break that behavior.
    • If unused, remove the declaration and import to avoid lint/TS errors like noUnusedLocals.
  2. 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 getRequiredReferenceRules uses useI18n or other composables internally, do not call it from the template/computed getter; refactor it to accept t or call it in setup.

  3. Verify rule parity
    Confirm getRequiredReferenceRules(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.

  4. Check model correctness and reactivity

    • Ensure model is the expected argument for getRequiredReferenceRules.
    • If model can be undefined or 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.
  5. Import path

    • Verify @/workflow-canvas/component/node-cascader/index.vue exists 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-cascader if the project exposes one.
    • Check that no other files still import the old NodeCascader.vue path.
  6. Possible circular dependency

    • Confirm node-reference does not import the component or other UI code that imports node-reference, which could create a circular dependency.
  7. Formatting/lint

    • The new NodeCascader line is long; run the project formatter.
    • Check for unused imports such as computed or inject if this diff changed their usage.

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>

<!-- 输出思考 -->

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.
  • ref may 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 (the mk-required span is only visual; the mk-hide-asterisk class 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 validator whose field reference matches prop="image_list". If the validator validates a hard‑coded field name, binding it to image_list may validate nothing.
  • no useI18n() call at module/render scope inside node-reference; if it relies on injection it can warn/fail when invoked during template render. Global i18n.global.t is 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-reference inserted between ThinkingSetting and NodeModelSelect breaks the existing grouping; run ESLint import/order (or sort by path depth/case consistently).
  • Keep the <!-- 选择图片 --> comment — unchanged, good.
  • If getRequiredReferenceRules allocates arrays, make sure it doesn't mutate model or shared constants.
  • Add a brief JSDoc on the helper stating which prop name 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

  1. grep for imageCascaderRef and remove the leftover declaration / fix tests.
  2. Confirm getRequiredReferenceRules returns required: true, the same i18n key, and the same trigger.
  3. Cache the rules with computed.
  4. Decide on barrel export vs deep import.
  5. Confirm no circular import and that NodeCascader's public API is unchanged.
  6. Apply the same helper to the other reference fields for consistency.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants