Skip to content

fix: login setting number - #7967

Merged
wangdan-fit2cloud merged 2 commits into
v3from
pr@v3@feat_login_setting
Nov 17, 2026
Merged

wangdan-fit2cloud merged 2 commits into
v3from
pr@v3@feat_login_setting

Conversation

@shaohuzhang1

Copy link
Copy Markdown
Contributor

feat: tool i18n
fix: login setting number

@wangdan-fit2cloud
wangdan-fit2cloud merged commit ff15bf0 into v3 Nov 17, 2026
3 of 4 checks passed
@wangdan-fit2cloud
wangdan-fit2cloud deleted the pr@v3@feat_login_setting branch November 17, 2026 06:42
}
}
generateLocaleSchema()
}

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 bugs / correctness

  1. import.meta.main may silently disable the whole script.

    • It exists in Node ≥ 24.2 (and recent 22.x), but on older Node it is undefined. Since the entire validation + generation runs inside if (import.meta.main), the script would exit successfully without doing anything — a dangerous silent failure in CI.
    • Safer:
      const isMain =
        import.meta.main ??
        import.meta.url === pathToFileURL(process.argv[1]).href
  2. Direct .ts import of ../src/locales/config.ts.

    • This requires --experimental-strip-types (Node ≥ 22.6 / stable in ≥ 23.6) or allowImportingTsExtensions: true in tsconfig. If the project's tsconfig/module resolution doesn't allow it, the script won't compile. Worth verifying explicitly.
  3. Arrays are compared by length and index.

    • collectKeys recurses into arrays via Object.entries, so [a, b, c] vs [a, b] is flagged as a missing key, and a locale with a longer list reports “extra” keys. For i18n this is often unintended — plural forms or lists legitimately differ per language.
    • Decide whether arrays should be checked by element type only, ignored, or explicitly validated.
  4. Symlinked JSON files are silently skipped.

    • Dirent.isFile() returns false for symlinks. Files like common.json -> ../shared/common.json won't be picked up. Use existsSync on the joined path, or readdirSync without withFileTypes + statSync, if symlinks are possible.
  5. BOM in JSON files.

    • JSON.parse('\ufeff{...}') throws. If any locale file may be saved with a UTF-8 BOM, strip it before parsing (readFileSync(...).replace(/^\uFEFF/, '')).

Robustness

  1. localeKeys doesn't check directory existence.

    • readdirSync(join(localeRoot, locale)) will throw a bare ENOENT. Better to assert existence and produce a clear error:
      if (!existsSync(directory)) throw new Error(`语言目录不存在: ${directory}`)
    • Also good to verify every LOCALE_OPTIONS entry has a directory, and ideally warn about locale directories that exist but are not listed in LOCALE_OPTIONS.
  2. Temp file not cleaned up on failure.

    • If writeFileSync(temp, schema) or renameSync throws, ${output}.${pid}.tmp remains. Wrap in try/finally (or unlinkSync in finally).
  3. Error message conflates “read” and “parse” errors.

    • 无法读取语言包 ${path} is emitted for JSON.parse failures too. Either adjust the message (“读取或解析失败”) or check error instanceof SyntaxError.

Design / optimization

  1. Default locale is parsed twice.

    • generateLocaleSchema() reads only filenames, but localeKeys(DEFAULT_LOCALE) re-parses them for comparison. Extracting a loadFileEntries(dir) helper used by both would avoid double reads and keep filename/namespace logic in one place.
  2. First-error-wins is poor DX for CI.

    • Aggregate mismatches per locale (missing / wrong type / extra) and throw once at the end with a joined list. Much easier to fix in one pass than repeated runs.
  3. Mixed root keys: filenames vs namespaces.

    • The schema uses getLocaleNamespace(file) (e.g., common), but collectKeys seeds the root prefix with file (e.g., common.json). Both are internally consistent, but error messages and generated types use different identifiers, which is confusing. Consider seeding with the namespace for consistency.
  4. Extract validateLocales() from the import.meta.main block.

    • Makes it unit-testable and lets the main block stay trivial.
  5. schemaSourceDir export.

    • It's only used internally. Keep it non-exported unless an external consumer really needs it.
  6. kind type.

    • Map<string, string> works but a union would make the validator clearer and IDE-friendlier:
      type JsonKind = 'null' | 'array' | 'object' | 'string' | 'number' | 'boolean'
  7. Missing return types.

    • jsonFiles, collectKeys, localeKeys have inferred types; explicit annotations (string[], void, Map<...>) document intent cheaply.

Minor / style

  1. Comments and error messages are Chinese while the codebase's language is unclear. If the project's convention is English, translate them; otherwise ignore.

  2. fileURLToPath(new URL('../src/locales/', import.meta.url)) can be simplified with import.meta.dirname on Node ≥ 20.11, though the current form is fine.

  3. renameSync on the same directory is correct and the idempotent readFileSync(...) === schema guard is good — keep it. Just note that if schema.generated.d.ts is intended as a build artifact, it should be .gitignored; if committed for type-checking in CI, keep it committed.

  4. typeof import('./path.json') in the generated .d.ts requires resolveJsonModule in tsconfig — worth a comment in the generated header so future readers don't wonder.

Summary

The overall approach (Map-based filename→namespace dedup, temp-file+rename, idempotent write, key/type diffing) is solid. The main risks are the import.meta.main silent no-op, the .ts import requirement, and the strict per-index array comparison, which is likely to reject legitimate translations. Robustness improvements (directory existence, temp cleanup, aggregated errors) are small but valuable.

{{ editId ? t('common.actions.save') : t('common.actions.create') }}
</el-button>
</template>
</MkDrawer>

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: i18n refactor of McpFormDrawer

Overall the change is sensible: moving the hardcoded strings to vue-i18n, making formRules a computed so validation messages follow the locale, and disabling rule-change revalidation. A few real risks and several consistency nits below.


1. Correctness / potential issues

1.1 Stale validation messages after a locale switch

formRules is now a computed, and you correctly added :validate-on-rule-change="false" to avoid Element Plus re-validating every time the object identity changes. But this means already-rendered error messages keep the old language until the field is re-validated. If locale switching is supported at runtime, add:

const formRef = ref<FormInstance>()
const { locale } = useI18n({ useScope: 'global' })

watch(locale, () => {
  nextTick(() => {
    formRef.value?.clearValidate()          // or revalidate visible fields
  })
})

and bind ref="formRef" on <el-form>.

1.2 useI18n({ useScope: 'global' }) bypasses local scope

This is fine functionally, but:

  • If any unit test mounts the component with a locally provided i18n instance (e.g. provide/global.plugins mismatch), useScope: 'global' will fail to resolve and you'll get raw keys.
  • It prevents overriding messages via an <i18n> block later.

Since this component defines no local messages, the default useI18n() already resolves to the global scope — prefer that unless you have a specific reason. Also, any test that mounts this component now needs an i18n plugin installed, or it will throw.

1.3 Localized string inside new Error(...)

: Promise.reject(new Error(t('tool.messages.createUnsupported')))

Two concerns:

  • Error objects are usually logged / routed to a global handler; a localized message there is misleading in logs and can be double-reported if the handler also displays a toast.
  • If the global handler shows error.message directly, the wording is now coupled to the current locale at throw time.

Recommendation: keep the Error message in a neutral language (usually English) and localize only at the display layer:

: Promise.reject(new Error('Tool creation is not supported by this resource API'))

(or attach a code: Object.assign(new Error('...'), { code: 'CREATE_UNSUPPORTED' })).

1.4 Missing translation keys will surface the raw key to users

MsgError / MsgSuccess / MsgConfirm all render whatever t() returns. If any of these are missing in a locale, users will see tool.mcp.config.requiredMessage in a toast:

common.messages.saveSuccess
common.messages.createSuccess
common.messages.connectionSuccess
common.actions.testConnection
common.dialogs.notice
common.dialogs.unsavedChanges
common.labels.basicInfo
common.name.label
common.description.label
common.placeholders.input
tool.mcp.config.requiredMessage
tool.mcp.config.invalidMessage
tool.mcp.config.description
tool.mcp.name.requiredMessage
tool.mcp.name.placeholder
tool.mcp.serviceTitle
tool.messages.createUnsupported
resource.mcpConfig.title

Add a CI check for key parity across locale files (a small script or @intlify/unplugin-vue-i18n type generation) so missing keys fail the build instead of leaking into production.

1.5 Cross-namespace key reuse: resource.mcpConfig.title

Using resource.mcpConfig.title inside a tool form couples the tool module to the resource module. If someone edits that key for the resource-management screens, the tool drawer silently changes. Define a dedicated tool.mcp.config.title and keep the two in sync deliberately.


2. Naming / consistency issues

2.1 Mixed namespaces for the same concept

  • Label: common.name.label
  • Required message: tool.mcp.name.requiredMessage
  • Placeholder: tool.mcp.name.placeholder

That's three namespaces for the "name" field. Pick one owner per concept — I'd suggest keeping all MCP-specific strings under tool.mcp.*, and only truly global labels ("Cancel", "Save", "Basic Info") under common.*.

2.2 Key shape inconsistency

common.labels.basicInfo vs tool.mcp.serviceTitle — one uses labels.*, the other a flat *Title. Choose a single convention (*.title recommended) across the file.

2.3 Parentheses removed from the config hint

Original: (仅支持 SSE、Streamable HTTP 调用方式) — the parentheses were part of the string. If tool.mcp.config.description doesn't include them, the visual output changes. Also, the original had a leading full-width space; you replaced it with ml-1, which is the cleaner solution — just confirm the translation strings themselves are consistent (some locales may need a space, some not).


3. Other observations (mostly pre-existing)

  • Button disabled states are inconsistent: 取消 / 测试连接 are disabled on loading || formLoading, but the primary button is only :disabled="formLoading" (it relies on :loading="loading"). It works, but intent is unclear. Make them symmetric for readability.
  • 测试连接 is clickable with an empty code, which will always fail server-side. Consider :disabled="loading || formLoading || !mcpForm.code.trim()".
  • handleTestConnection has no .catch (only .finally). If the error isn't handled by a global interceptor, you get an unhandled rejection. Add .catch(() => {}) or show MsgError.
  • Localizing the title prop: props.title is still supplied by the caller — verify the parent component isn't passing a hardcoded Chinese string, or the drawer header stays untranslated.
  • mcpServerExample (the textarea placeholder) isn't localized — that's probably fine for a JSON sample, but confirm it isn't user-facing prose.
  • @blur="mcpForm.name = mcpForm.name.trim()" mutates state inline; harmless here, but if name could ever be null/undefined this throws. Prefer @blur="mcpForm.name = (mcpForm.name ?? '').trim()".
  • useI18n before defineProps is valid (still inside setup), just slightly unusual ordering; no issue.
  • computed<FormRules<McpFormModel>> is fine, but note that computed returns a new object identity on every locale change, so anything downstream that does watch(rules, ...) will fire (Element Plus does, which is why validate-on-rule-change=false was needed — good catch).

4. Suggested small patch

// Prefer default scope unless you really need global
const { t, locale } = useI18n()

const formRef = ref<FormInstance>()

// Clear stale validation text when the language changes
watch(locale, () => nextTick(() => formRef.value?.clearValidate()))

// Keep Error messages neutral; localize at the UI layer
: Promise.reject(new Error('CREATE_NOT_SUPPORTED'))
<el-form
  ref="formRef"
  v-loading="formLoading || loading"
  :model="mcpForm"
  :rules="formRules"
  :validate-on-rule-change="false"
  ...
>

5. Summary

Severity Item
Medium Missing-key risk → raw keys shown to users; add key-parity check
Medium Localized message inside new Error — prefer codes/neutral messages
Medium Stale validation messages after locale switch (validate-on-rule-change=false)
Low useScope: 'global' hard-codes scope and complicates tests
Low Cross-namespace reuse of resource.mcpConfig.title
Low Inconsistent key namespaces for the same "name" field
Nit Parentheses/space change in config hint; inconsistent button disabled states; missing .catch on test connection

The core i18n mechanics are correct — the computed rules are the right approach, and disabling automatic rule-change validation is the right companion change. The remaining work is mostly around key organization, test/mock readiness, and avoiding localized text inside error objects.

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