Skip to content

refactor: finalize internationalization cleanup - #8075

Merged
wangdan-fit2cloud merged 1 commit into
v3from
pr@v3@feat_translation_final
Nov 21, 2026
Merged

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

Conversation

@shaohuzhang1

Copy link
Copy Markdown
Contributor

refactor: finalize internationalization cleanup

],
},
} satisfies Record<string, LogicFlow.GraphConfigData>
}) satisfies Record<string, LogicFlow.GraphConfigData>

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 Changes

1. reactive() wrapping breaks satisfies semantics — type issue

export const applicationTemplate = reactive({...}) satisfies Record<string, LogicFlow.GraphConfigData>

reactive() returns a UnwrapNestedRefs<T> type. In practice, Vue's reactive proxy unwraps refs on access, but at the type level the computed() refs are still stored as ComputedRef. This means:

  • Any code reading applicationTemplate.assistant.nodes[0].properties.stepName will get a ComputedRef<string> (typed), not a string — downstream typing gets messy.
  • Serialization (JSON.stringify) of a reactive object containing computed refs will not produce the underlying string; it will likely output an empty/opaque object or throw depending on Vue's version. If this template is ever persisted or sent to an API, this is a bug.

Recommendation: Keep the template as a plain factory function that evaluates translations at call time:

export const createApplicationTemplate = () =>
  ({ blank: {...}, assistant: {...} }) satisfies Record<string, LogicFlow.GraphConfigData>

This gives fresh translated values per instantiation, keeps it plain-data (serializable), and avoids reactive-ref leakage into consumers.

2. Translation timing / reactivity

If you intend these labels to update on locale change, using static computed() at module load binds them once — but since they're captured in a plain object, they won't re-render unless consumers read .value inside the template. Given the earlier serialization concern, a factory returns the freshly-translated value per use, which is usually the desired behavior for templates.

3. Inconsistent node-id interpolation via translation

knowledgeReference: `{{${t('workflow.searchKnowledge.label')}.data}}`
questionReference: START_NODE_REFERENCES.question,
  • Using a translated label to build a node reference ({{知识库检索.data}}) is fragile: if the locale changes the label, the reference no longer matches the actual node id/stepName. Node references should be stable identifiers, not localized labels. Similarly, START_NODE_REFERENCES.question suggests a constant exists — apply the same pattern for the knowledge node.
  • Mixing hard-coded {{...}} string construction with START_NODE_REFERENCES is inconsistent.

Fix: Define both references as constants (e.g., KNOWLEDGE_NODE_REFERENCES.data, START_NODE_REFERENCES.question) and pass them through i18n only if the prompt text itself needs localization, keeping the reference tokens language-independent.

4. Translation key for step name concatenation

stepName: computed(() => `${t('workflow.reply.label')}1`)

Concatenating a numeral onto a translated string is locale-fragile (word order, pluralization, separators). Prefer a dedicated key like workflow.reply.label1 or a parameterized t('workflow.reply.labels.copy', { index: 1 }).

5. Removed unnecessary reactive() (good)

- reactive({ label: computed(...), value: 'answer' }),
+ { label: computed(...), value: 'answer' },

Correct cleanup — nested plain objects don't need their own reactive. The top-level reactive already deep-proxies.

6. defaultApplicationNodes shared reference

blank: { edges: [], nodes: defaultApplicationNodes },

Still shares a reference to defaultApplicationNodes. With reactive, mutations via one template may leak across consumers. Deep-clone or use a getter/factory: nodes: structuredClone(defaultApplicationNodes) (or your project's clone utility).

7. Missing fields / possible copy-paste issues

  • chatFields: [] retained alongside populated fields/globalFields — verify intended.
  • The reply node uses fields: [] with content set — confirm the reply content isn't expected in fields.
  • Double-check that every new i18n key (workflow.searchKnowledge.segmentList, application.template.assistant.userPrompt, etc.) actually exists in all locale files, otherwise users see raw keys.

8. Minor

  • Consider extracting the repeated computed(() => t('workflow.history.label')) into a local helper (const labelOf = (key) => computed(() => t(key))) to reduce noise and typos across ~30 occurrences.

Summary of Priority Fixes

  1. High: Don't build node references from translated labels; use stable id constants (both start & knowledge nodes).
  2. High: Reconsider reactive() around a static config — prefer a factory returning plain serializable data.
  3. Medium: Avoid string concatenation on translated text (stepName + 1).
  4. Medium: Clone defaultApplicationNodes to avoid shared mutation.
  5. Low: Verify all i18n keys exist; extract a labelOf helper.

],
},
} satisfies Record<string, LogicFlow.GraphConfigData>
}) satisfies Record<string, LogicFlow.GraphConfigData>

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.

Here is an analysis of the code changes, highlighting potential issues and optimization suggestions.

1. Critical Issue: Invalid computed Usage in Data Structures

Problem: The most significant issue is placing Vue's computed() directly inside a plain object structure that is then passed to reactive().

  • How computed works: In Vue 3, computed() returns a ref/object that represents a computation logic, not the value itself. However, the third party library (LogicFlow) likely expects the properties of nodes/edges to be plain data objects (strings, numbers, etc.) at the time of initialization or during reactive updates.
  • The Problem:
    • stepName: computed(() => ...) results in stepName being a ComputedRef object (e.g., { _value: ..., _dirty: ... }), not a string.
    • Unless LogicFlow explicitly supports Vue Refs/Computed values in its configuration schema (which is rare for generic graph libraries), it will fail to render labels, treat them as [object Object], or crash.
    • Wrapping the entire exported constant with reactive() does not automatically unwrap nested computed refs when passed to external libraries unless the library uses deep unwrapping (which typical Canvas/SVG rendering libraries do not).

Recommendation:
Do not use computed() inside static template data structures intended for graph engines like LogicFlow. Instead, handle localization at the rendering layer or ensure the data passed to LogicFlow is plain strings.

If you must keep the structure reactive:
Option A (Recommended): Keep the original structure plain and transform it before passing to LogicFlow.
Option B: If LogicFlow supports custom reactive props (unlikely), ensure the component using LogicFlow accesses .value properly, but this is fragile.

2. Type Safety & TypeScript Issues

Problem:

export const knowledgeTemplate = reactive({ ... }) satisfies Record<string, LogicFlow.GraphConfigData>
  • satisfies with reactive() can cause type inference mismatches if the shape of reactive's return type doesn't strictly match GraphConfigData due to Vue's internal proxies or if computed refs interfere with the expected string types for label/name.
  • Since computed() returns a ComputedRef<string>, TypeScript will complain if LogicFlow.GraphConfigData expects stepName?: string. This confirms the type mismatch noted in point build(deps): bump the pip group across 1 directory with 2 updates #1.

Recommendation:
Define the base template as a type-aligned constant (without Vue reactivity) first, then create a separate computed getter that generates a localized copy for the UI.

3. Unnecessary Reactivity / Performance Overhead

Problem:
Wrapping a large, mostly static configuration object with reactive() is performance-intensive and semantically incorrect.

  • reactive() creates a Proxy over all deeply nested properties. For a complex graph definition, this adds unnecessary overhead.
  • These templates are likely constants that don't change per-instance unless the language changes. They do not need global reactive tracking on every single field (height, width, type, etc.). Only the text fields need localization.

Recommendation:
Keep the base template as a plain object.

4. Localization Strategy Flaw

Problem:
The current approach mixes translation logic directly into the template data structure. If t() depends on the current locale, and the locale changes at runtime, LogicFlow might not reactively update the canvas unless it manually polls these values.

Recommendation:
Use a factory function or a computed wrapper outside the template.

Suggested Refactor Pattern

Instead of modifying the raw template export, create a hook or computed property that generates the localized version:

import { computed, unref } from 'vue'
import type LogicFlow from '@logicflow/core'
import { t } from '@/locales'

// 1. Keep the raw template as plain data (no Vue imports, no reactive/computed inside)
export const rawKnowledgeTemplate = {
  default: {
    nodes: [
      {
         // ... other props
         properties: {
           stepName: 'common.labels.basicInfo', // Store Translation KEY, not t() result
           displayText: null // placeholder
         }
      },
      // ... rest of nodes
    ]
  }
} satisfies Record<string, LogicFlow.GraphConfigData>

// 2. Create a helper to inject translations
function replaceLabels(node: any): any {
  if (!node.properties) return node
  
  // Helper to resolve translation keys
  const resolveProp = (obj: any, key: string, locKey: string) => {
    if (obj[key] && typeof obj[key] === 'string') {
       // Assume the stored string is a translation key if it looks like one, 
       // or add a specific field like 'i18nKey' to distinguish.
       // Better practice: Add a separate `i18nStepName` field in your interface
    }
  }

  // More robust approach: Modify data structure to hold i18n keys separately
  return {
    ...node,
    properties: {
      ...node.properties,
      // Assuming you added an i18n key field in your raw template
      stepName: node.properties.i18nStepName 
                 ? t(node.properties.i18nStepName) 
                 : node.properties.stepName
    }
  }
}

// 3. Export a localized version (computed based on language)
export const localizedKnowledgeTemplate = computed(() => {
  // Deep clone and map translations
  const lang = t('lang.current') || 'en' // Access language to trigger reactivity
  return cloneAndTranslate(rawKnowledgeTemplate)
})

Summary of Actions

  1. Revert computed() usage: Do not put computed() inside the knowledgeTemplate object. It breaks type safety and library compatibility.
  2. Store Keys, Not Values: In the raw template, store translation keys (e.g., 'common.labels.basicInfo') instead of calling t().
  3. Transform Before Use: Create a computed property or function that takes the raw template, traverses it, replaces keys with t(key), and passes the resulting plain object to LogicFlow.

config: { fields: [{ label: computed(() => t('workflow.document.list')), value: 'document_list' }] },
},
})

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 provided diff demonstrates a refactoring effort to centralize i18n keys and reduce redundancy, but there are specific points of concern and optimization suggestions.

1. Consistency & Irregularities

  • Inconsistent Key Naming:

    • Most changes replace node-specific result labels (e.g., workflow.node.result) with a global one (common.labels.result). This is good for consistency.
    • However, in searchDocumentNode and documentExtractNode, the "document list" label is changed to workflow.document.list.
    • Issue: Why isn't document_list using a common key like common.labels.documents or similar? It mixes knowledge.list (seemingly from a different domain namespace) and workflow.document.list. Ensure workflow.document.list exists and is correctly translated.
    • Suggestion: If "document list" is used across multiple nodes outside of just the workflow context, consider moving it to common as well. If it's strictly workflow-specific, keep it as is, but ensure knowledge.list is also checked for consistency (why use knowledge.list instead of workflow.knowledge.list or common.knowledge.list?).
  • Missing i18n Keys Check:

    • Verify that t('common.labels.result'), t('knowledge.list'), and t('workflow.document.list') exist in your locale files (e.g., en.json, zh-CN.json). Missing keys will result in raw keys being displayed in the UI.

2. Potential Issues

  • Loss of Contextual Specificity (Minor):
    • Changing workflow.searchDocument.documentList -> knowledge.list might remove contextual clarity if "knowledge list" is interpreted differently in other parts of the app. Ensure this label accurately represents the data passed from searchDocumentNode.
  • Reactive Object Performance (Negligible but Noted):
    • You are using computed() inside reactive() objects for label and stepName. This is correct for Vue 3 reactivity. However, creating many computed properties adds slight overhead. Since t() (i18n function) is likely already reactive or stable after initialization, ensure t is not unnecessarily triggering re-renders. In most i18n setups (like vue-i18n), t is reactive only when language changes, so this is safe.

3. Optimization Suggestions

A. Reduce Boilerplate with a Helper Function

There is significant repetition in:

config: { fields: [{ label: computed(() => t('...')), value: '...' }] }

Suggestion: Create a helper function to generate these field definitions.

// Example helper
import type { ComputedRef } from 'vue';

function createResultField(labelKey: string, value: string = 'result') {
  return {
    label: computed(() => t(labelKey)),
    value,
  };
}

// Usage
export const speechToTextNode = reactive({
  // ... other props
  properties: {
    stepName: computed(() => t('workflow.speechToText.label')),
    config: { 
      fields: [createResultField('common.labels.result')] 
    },
  },
})

B. Centralize Common Configs

Since many nodes now use the exact same config structure (fields: [{ label: ..., value: 'result' }]), consider defining reusable config objects if they are identical.

C. Validate Translation Keys

Run a script to check if all new keys (common.labels.result, workflow.document.list, knowledge.list) are present in all locale files to prevent missing translations in production.

Summary of Changes Review

Change Verdict Notes
workflow.node.result → common.labels.result ✅ Good Improves consistency; reduces duplication.
workflow.searchDocument.knowledgeList → knowledge.list ⚠️ Check Ensure namespace knowledge is appropriate here. Is it a global domain or workflow-specific?
workflow.*.documentList → workflow.document.list ✅ Neutral Standardizes under workflow.document.
Repeated computed(() => t(...)) 💡 Optimize Use a helper function to reduce code redundancy.

Final Recommendation: The change is logically sound for maintainability. Proceed after verifying that all referenced translation keys exist in your i18n resources.

@wangdan-fit2cloud
wangdan-fit2cloud merged commit fdf6a33 into v3 Nov 21, 2026
3 of 4 checks passed
@wangdan-fit2cloud
wangdan-fit2cloud deleted the pr@v3@feat_translation_final branch November 21, 2026 13:48
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