Repository navigation
fix: login setting number - #7967
Conversation
| } | ||
| } | ||
| generateLocaleSchema() | ||
| } |
There was a problem hiding this comment.
Code Review
Potential bugs / correctness
-
import.meta.mainmay 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 insideif (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
- It exists in Node ≥ 24.2 (and recent 22.x), but on older Node it is
-
Direct
.tsimport of../src/locales/config.ts.- This requires
--experimental-strip-types(Node ≥ 22.6 / stable in ≥ 23.6) orallowImportingTsExtensions: truein tsconfig. If the project's tsconfig/module resolution doesn't allow it, the script won't compile. Worth verifying explicitly.
- This requires
-
Arrays are compared by length and index.
collectKeysrecurses into arrays viaObject.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.
-
Symlinked JSON files are silently skipped.
Dirent.isFile()returnsfalsefor symlinks. Files likecommon.json -> ../shared/common.jsonwon't be picked up. UseexistsSyncon the joined path, orreaddirSyncwithoutwithFileTypes+statSync, if symlinks are possible.
-
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
-
localeKeysdoesn't check directory existence.readdirSync(join(localeRoot, locale))will throw a bareENOENT. Better to assert existence and produce a clear error:if (!existsSync(directory)) throw new Error(`语言目录不存在: ${directory}`)
- Also good to verify every
LOCALE_OPTIONSentry has a directory, and ideally warn about locale directories that exist but are not listed inLOCALE_OPTIONS.
-
Temp file not cleaned up on failure.
- If
writeFileSync(temp, schema)orrenameSyncthrows,${output}.${pid}.tmpremains. Wrap intry/finally(orunlinkSyncinfinally).
- If
-
Error message conflates “read” and “parse” errors.
无法读取语言包 ${path}is emitted forJSON.parsefailures too. Either adjust the message (“读取或解析失败”) or checkerror instanceof SyntaxError.
Design / optimization
-
Default locale is parsed twice.
generateLocaleSchema()reads only filenames, butlocaleKeys(DEFAULT_LOCALE)re-parses them for comparison. Extracting aloadFileEntries(dir)helper used by both would avoid double reads and keep filename/namespace logic in one place.
-
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.
-
Mixed root keys: filenames vs namespaces.
- The schema uses
getLocaleNamespace(file)(e.g.,common), butcollectKeysseeds the root prefix withfile(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.
- The schema uses
-
Extract
validateLocales()from theimport.meta.mainblock.- Makes it unit-testable and lets the main block stay trivial.
-
schemaSourceDirexport.- It's only used internally. Keep it non-exported unless an external consumer really needs it.
-
kindtype.Map<string, string>works but a union would make the validator clearer and IDE-friendlier:type JsonKind = 'null' | 'array' | 'object' | 'string' | 'number' | 'boolean'
-
Missing return types.
jsonFiles,collectKeys,localeKeyshave inferred types; explicit annotations (string[],void,Map<...>) document intent cheaply.
Minor / style
-
Comments and error messages are Chinese while the codebase's language is unclear. If the project's convention is English, translate them; otherwise ignore.
-
fileURLToPath(new URL('../src/locales/', import.meta.url))can be simplified withimport.meta.dirnameon Node ≥ 20.11, though the current form is fine. -
renameSyncon the same directory is correct and the idempotentreadFileSync(...) === schemaguard is good — keep it. Just note that ifschema.generated.d.tsis intended as a build artifact, it should be.gitignored; if committed for type-checking in CI, keep it committed. -
typeof import('./path.json')in the generated.d.tsrequiresresolveJsonModulein 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> |
There was a problem hiding this comment.
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.pluginsmismatch),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.messagedirectly, 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 onloading || 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 emptycode, which will always fail server-side. Consider:disabled="loading || formLoading || !mcpForm.code.trim()".handleTestConnectionhas no.catch(only.finally). If the error isn't handled by a global interceptor, you get an unhandled rejection. Add.catch(() => {})or showMsgError.- Localizing the
titleprop:props.titleis 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 ifnamecould ever benull/undefinedthis throws. Prefer@blur="mcpForm.name = (mcpForm.name ?? '').trim()".useI18nbeforedefinePropsis valid (still inside setup), just slightly unusual ordering; no issue.computed<FormRules<McpFormModel>>is fine, but note thatcomputedreturns a new object identity on every locale change, so anything downstream that doeswatch(rules, ...)will fire (Element Plus does, which is whyvalidate-on-rule-change=falsewas 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.
feat: tool i18n
fix: login setting number