Skip to content

feat: internationalize knowledge base settings - #7993

Merged
wangdan-fit2cloud merged 1 commit into
v3from
pr@v3@feat_translation2
Nov 18, 2026
Merged

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

Conversation

@shaohuzhang1

Copy link
Copy Markdown
Contributor

feat: internationalize knowledge base settings

{{ t('common.actions.save') }}
</el-button>
</div>
</template>

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

Correctness / functional issues

  1. knowledgeTypeKey may produce an invalid i18n key — KNOWLEDGE_TYPE_MAP[knowledge.value.type].toLowerCase() assumes the mapped value is a string that matches your i18n key namespace (e.g. base, web). If the map ever yields something like web_site or an enum name, t('knowledge.<x>.label') silently falls back to the raw key. Consider asserting this at compile time with a typed union, or keep a mapping constant for keys.

  2. i18n fallback noise — if knowledgeTypeKey is '' (when knowledge.value is null before mount), you call t('knowledge..label'). The template already guards on knowledge.type, but the computed can still emit a bad key once. Return null/guard instead.

  3. settingRules converted to computed — since it now depends on t, it is reactive to locale changes, which is good. However Element Plus caches validation messages in some paths; adding :validate-on-rule-change="false" is a sensible mitigation, but confirm that re-validation on locale switch isn't desired (otherwise flip it to true).

  4. Nested label interpolation — t('common.validation.inputFieldRequired', { label: 'App ID' }) hardcodes English labels inside Chinese sentences ("请输入 App ID"). For Folder Token, App Secret etc. verify the translated target sentence reads naturally; better to make these proper i18n keys (e.g. knowledge.fields.appId.label) rather than passing literals.

  5. Removed static rule message for source_url — previously there was also a distinct required message; now t('knowledge.fields.webRootUrl.requiredMessage') must exist, otherwise the user sees a raw key. Check the resource file.

  6. Locale change + existing validation state — when the user switches locale while the form has errors, previously displayed error messages don't re-render from the computed rules; only new validations use the new text. Not a bug but worth documenting or triggering settingFormRef.value?.clearValidate() on locale change if consistent messaging matters.

  7. Missing watch on locale for setTingRules side effects — no issue for rules (they're read at validation time), but the t() calls inside handleSave (MsgConfirm) run at click time so they always use the current locale — fine.

  8. useI18n({ useScope: 'global' }) — correct for global messages, but if the component's originals were resolved under a component scope, the keys may not resolve. Verify all keys exist in the global locale files (not scoped blocks).

Minor / style

  1. Placeholder count in removed code: placeholder="默认为 body..." → t('knowledge.fields.selector.placeholder') — ensure the default body hint survives translation.
  2. Inconsistent spacing: (MB) kept as literal after fileSizeLimit.label; consider embedding unit in translation for locales where the unit placement differs.
  3. Named import order — a stylistic note: importing useI18n after lodash breaks any alphabetized import convention; run your linter/formatter.
  4. Trailing comma / formatting — the multi-line folder_token rule array is fetched by prettier-normal conventions; verify prettier passes.

Performance

  1. settingRules computed recreates rule objects every time any reactive dep changes; since it only depends on the locale normally, this is negligible. No further optimization needed.
  2. No unnecessary watch added — good.

Optimization suggestions

  1. Introduce a strongly-typed helper for field-label translations to avoid repeat 'App ID' literal strings:
    const fieldLabel = (key: string) => t(`knowledge.fields.${key}.label`)
  2. Add a lint rule / TS check ensuring every t('...') key appears in the AST-scanned key list (most projects have one); it would have caught build(deps): bump the pip group across 1 directory with 2 updates #1/关于页面优化 #5.
  3. Consider centralizing the knowledge-type → i18n-key mapping in @/constants/knowledge so the view doesn't rely on .toLowerCase().

Overall

No blockers in what's shown, but items #1, #2, #4, #5 are the highest risk (bad keys or mixed-language strings). The rest are quality improvements.

@wangdan-fit2cloud
wangdan-fit2cloud merged commit 3fec595 into v3 Nov 18, 2026
3 of 4 checks passed
@wangdan-fit2cloud
wangdan-fit2cloud deleted the pr@v3@feat_translation2 branch November 18, 2026 04:47
{{ t('common.actions.save') }}
</el-button>
</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.

Code Review

Potential Issues

  1. t() overload misuse (likely a bug)

    t('knowledge.scheduledSync.interval.minHoursMessage', { count: minimum }, minimum)

    The third argument minimum is passed but i18next/vue-i18n typically ignores it. If the intent was pluralization, use the options form:

    t('...', { count: minimum })

    Also confirm the translation string uses {{count}} and not positional interpolation.

  2. Computed invalidation of scheduleOptions depends on locale
    computed re-evaluates only when its reactive deps change. t(...) here is called inside a computed — verify that t internally accesses reactive locale state (vue-i18n does via locale.value), otherwise labels won't update on language switch. In vue-i18n v9 this works; in some setups (e.g., using i18n.global.t), you must reference locale.value.

  3. period.labelKey fallback logic inconsistent with children
    Top-level falls back to period.label, children fall back to option.label. Verify both labelKey/label exist on all entries, otherwise a cascader option may render undefined.

  4. Monthly label assumes day suffix format

    `${option.value} ${t('common.schedule.day')}`

    Hardcoding value before translated unit loses flexibility (e.g., RTL languages or languages where the unit precedes the number). Prefer an interpolated key: t('common.schedule.dayValue', { day: option.value }).

  5. Nested ternary readability
    The month/cron branch is hard to parse. Extract to a helper:

    const resolveChildLabel = (period, option) =>
      period.value === SCHEDULE_TYPE.MONTHLY
        ? t('common.schedule.dayValue', { day: option.value })
        : t(option.labelKey ?? '', option.label ?? '')
  6. Rule: days max for MONTHLY uses 31 — correct, but weekly max 7
    Weekly max of 7 is fine if days are 1–7 (ISO), but ensure backend/logic agrees (some systems use 0–6). Confirm off-by-one.

  7. Custom validator locale capture
    The validator closure calls t(). If rules are defined at module/setup top-level once, error messages won't refresh on locale change until a new validation run. Trigger formRef.value?.clearValidate() (or re-validate) on locale change if you want live updates.

  8. Optional chaining on cron_expression
    setting.cron_expression?.trim().split(/\s+/).length !== 5 — if cron_expression is '', .trim().split() yields [''] length 1, still fails as intended. Fine, but consider an explicit empty check for a clearer message.

  9. Number.isInteger(setting.interval_value) — if interval_value comes from an input as string, this rejects valid numeric input. Ensure model type is number or coerce first.

Minor / Suggestions

  • Extract magic regex:
    const TIME_REGEX = /^([01]\d|2[0-3]):[0-5]\d$/
  • Repeated syncSetting.schedule_type === SCHEDULE_TYPE.CRON in template — compute once:
    const isCronMode = computed(() => syncSetting.value.schedule_type === SCHEDULE_TYPE.CRON)
    Reduces noise and improves template readability.
  • MsgSuccess(t('common.messages.saveSuccess')) — good, keep consistent. Check other literal strings in the same file (comments, tooltips) for missed translations.
  • SCHEDULE_OPTION immutability — mapping creates new objects each time ({...period}); since scheduleOptions is recomputed frequently, consider memoize-style approach keyed on locale.value if this list is large. Not urgent.
  • Validator returns Error(error) — could just be callback(error || undefined). FormRules accepts string too; using new Error is fine but unnecessary.
  • Placeholder on el-cascader with clearable: after clearing, cascader shows placeholder correctly; ensure scheduleValue getter handles the cleared case (returning []) without throwing.

Overall

The i18n refactor is clean and consistent. The main concerns are (a) the third argument passed to t() in interval messages, (b) reactivity of scheduleOptions under locale changes, (c) nested-ternary readability, and (d) verifying day index ranges match the backend contract.

<el-table-column :label="t('common.labels.duration')" width="110">
<template #default="{ row }">{{ (row.duration_seconds ?? row.duration_ms / 1000).toFixed(2) }}s</template>
</el-table-column>
</MkTable>

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.

Code Review

Issues Found

1. Bug: syncStatusOptions was made computed but is still indexed directly as an object

<MkStatusLabel v-if="syncStatusOptions[row.status ...]" v-bind="syncStatusOptions[row.status ...]" />

Since syncStatusOptions is now a Ref<...>, in the template you must access .value (or rely on auto-unwrap). Vue auto‑unwraps top‑level refs only when used directly, so syncStatusOptions[someKey] indexes into the ref object itself, not the unwrapped value — this will evaluate to undefined. Fix by explicitly unwrapping:

const statusMap = computed(...) // or keep name
// template:
v-if="syncStatusOptions[row.status]"      // broken
v-if="syncStatusOptions.value[row.status]" // still broken in template? see below

Actually Vue's template compiler does auto‑unwrap top‑level refs even for property/index access in <script setup> templates, so syncStatusOptions[x] may work — but it's fragile and confusing. Safer: destructure a plain getter:

const syncStatusOptions = computed(() => ({...}))

and in template use syncStatusOptions.value[...] explicitly, or better, add a small helper:

function getStatusOption(status: KnowledgeSyncStatus) {
  return syncStatusOptions.value[status]
}

2. Possible bug: string interpolation in documents i18n key

return `${t('knowledge.stats.documents', log.total_count)}: ${log.total_count} (...)`
  • t(..., log.total_count) passes a number as the params argument. Many i18n libs (vue-i18n) require an object ({ count: n }) or named params; passing a raw number may fail silently or produce {[object Object]}.
  • You then append : ${log.total_count} again — the count appears twice if the translation already includes it (e.g. "共 {count} 个文档"). This likely yields "共 5 个文档: 5 (...)".

Fix:

return t('knowledge.syncLog.counts.summary', {
  total: log.total_count,
  details: counts.join(', '),
}) 

with a translation like "共 {total} 个文档 ({details})".

3. Inconsistent separator / locale handling

  • Original used Chinese ,; new code hardcodes ', '. Fine for English but not locale‑aware. Consider using an i18n list separator or the existing translation strings.

4. Fragile message matching still hardcoded in Chinese‑independent logic

if (/already running|still running|already queued/.test(log.message))
if (log.message === 'Scheduled synchronization is disabled')

These match against raw backend English messages. That's okay, but:

  • The regex doesn't account for case (/i missing) or minor wording changes.
  • Better: have the backend return a stable error/status code (e.g. skip_reason: 'task_in_progress' | 'scheduled_disabled') and switch on that instead of parsing text. This decouples UI from message wording.

5. Repeated row.status as KnowledgeSyncStatus cast

The cast is repeated three times in the template. Extract once:

<template #default="{ row }">
  <MkStatusLabel
    v-if="getStatusOption(row.status)"
    v-bind="getStatusOption(row.status)"
  />
</template>

6. t() inside computed — reactivity of locale

Good change overall (makes labels locale‑reactive), but ensure t is reactive in your setup (vue-i18n's useI18n() t is). If t was imported statically (not from useI18n), the computed won't re‑run on locale change. Verify.

7. Magic widths (width="200", "400", "120", "110")

Unchanged, but consider extracting layout constants or using responsive/min‑width where appropriate. Minor.

8. Minor formatting nit

Aligned diff lines are fine, but the object literal inside computed is now several long lines — consider multi‑line formatting for readability.

Summary Table

# Severity Item
1 High syncStatusOptions[...] indexing on a Ref — verify auto‑unwrap
2 High t(key, number) param + duplicated count in output
3 Low Hardcoded ', ' separator not locale‑aware
4 Medium Regex/string matching on backend messages — prefer codes
5 Low Repeated cast — extract helper
6 Medium Confirm t is from useI18n (reactive)
7 Low Magic numbers for column widths

The most important fix is #2 (double count / wrong i18n params) and confirming #1 behaves correctly at runtime with your Vue/i18n versions.

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