Repository navigation
feat(frontend): add en/zh-CN i18n via vue-i18n curated catalogs (ADR-0013) - #156
Conversation
|
You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard. |
voidvec
left a comment
There was a problem hiding this comment.
评审总结
先说结论:设计扎实,CI 全绿。下列意见中只有 [MAJOR] 建议合并前处理,其余可作为 follow-up。
services/locale.ts 这个依赖注入方案是本 PR 最好的决策 —— service 层不反向依赖 vue-i18n,node-env 单测零改动,同时兑现了「一个开关驱动 page chrome 和 error messages」。属性测试从「单一 zh-CN」升级为「任一已登记 locale × 任一 code」的笛卡尔积、i18nKeys.test.ts 用 import.meta.glob('?raw') 扫描调用点补上 tsc 检查不到模板的盲区,都是很实用的机械门禁。CJK 残留我复核了一遍,确认干净(仅剩 LocaleSwitcher 有意保留的 中文 短标签)。
[MAJOR] 错误消息在产生时被固化,切换语言后不更新
这与 ADR-0013 的核心主张冲突。ADR 第 22 行写的是:
One language switcher per app drives both page chrome and error messages
但实际行为是只有新产生的错误跟随语言,已经渲染的错误是静态快照。两个应用合计约 30 处调用点把 .message 直接存入响应式状态,例如 frontends/user/src/stores/auth.ts:48,66、frontends/user/src/pages/account/SecurityPage.vue 的 showError(normalizeError(e).message)(7 处)、frontends/admin/src/stores/auth.ts:161,201、frontends/admin/src/pages/roles/RolesPage.vue:39,59,82,95。
后果:用户在登录页看到 "Incorrect username or password" → 切到中文 → 这条报错仍然是英文,必须重新触发一次才会变中文。而这恰恰是最常见的实际使用场景(看不懂才去切语言)。
为什么测试没抓到:tests/e2e/i18n.spec.ts 的 "error messages follow the UI locale" 用例是先 addInitScript 设 zh-CN 再触发错误,只覆盖了「先切后错」,没覆盖「先错后切」。
根因是两个因素叠加,只修一个不够:
- 错误状态存的是已解析的
message字符串,而非NormalizedError.code; services/locale.ts里current是普通let变量,非响应式 —— 即使改成渲染时调用getErrorMessage(code),Vue 也追踪不到依赖,切换语言不会触发重渲染。
两个可选方向,取决于你们想不想为它付这点复杂度:
- 方案 A(接受现状,改文档):把 ADR-0013 与 PR 描述里的 "drives page chrome and error messages" 改成 "newly surfaced error messages follow the active locale",并补一条 e2e 明确锁定「先错后切不重译」这个行为,避免后人误以为已闭环。
- 方案 B(真正闭环):把 locale 提升为 vue
ref(放在src/i18n/而非services/,保持 service 层纯净),错误状态改存code,渲染时computed(() => { void localeRef.value; return getErrorMessage(code.value) })。
我倾向 B,但成本确实比 A 高,你们定。
[MINOR] vue-i18n message compiler 未预编译
catalog 里插值语法用得不少(admin en.ts 中 {name} / {total} / {count} 等 20+ 处,user 端也有 account.security.passkeys.defaultName 这类带参数的 key)。两端 vite.config.ts 都只有 vue() + tailwindcss(),默认 import vue-i18n 会带上运行时 message compiler,既有体积成本,也有每个 key 首次 t() 的编译开销。
接入 @intlify/unplugin-vue-i18n 做 AOT 预编译、配合 runtime-only 入口即可消除 —— 顺带把 PR 描述里列为 follow-up 的 bundle-size budget 一起解决。(因 vite.config.ts 不在本次 diff 内,故放在这里而非行内。)
[NIT] LoginPage.vue 的邮箱 placeholder 未提取
frontends/user/src/pages/auth/LoginPage.vue 里 password 的 placeholder 提取成了 auth.login.passwordPlaceholder,但 placeholder="you@example.com" 保持硬编码。邮箱示例通常不需要翻译,只是想确认是有意为之。(该行不在本次 diff 内。)
另见 7 条行内评论。
| // Resolve the protocol error code through the shared message catalog | ||
| // (covers every OAuth2/OIDC code; unknown codes fall back to the generic | ||
| // message) instead of rendering error_description raw. | ||
| error.value = getErrorMessage(errorParam) |
There was a problem hiding this comment.
[MAJOR] 这里就是「错误消息提前固化」的一个具体实例:getErrorMessage(errorParam) 在 onMounted 里求值一次后存入 error,之后语言切换不会影响它。
有意思的是这段注释写的是 "Resolve the protocol error code through the shared message catalog",思路完全正确 —— 只差把 code 存下来、把解析推迟到渲染时。全局约 30 处同类调用点,详见 review 正文。
| const root = ref<HTMLElement | null>(null) | ||
|
|
||
| // Native endonyms — shown identically in every locale (i18n convention). | ||
| const NATIVE_LABELS: Record<AppLocale, string> = { |
There was a problem hiding this comment.
[MINOR] 在 setup 顶层调用 t() 会得到静态快照,之后不再更新。切到 zh-CN 后,下拉里的 NATIVE_LABELS 仍是初始语言求值的结果。
目前两个 catalog 的 endonym 恰好一致(en 表 ui.locale.zhCN: '简体中文',zh-CN 表相同),所以缺陷不可见;但一旦有人按常规做法把 en 表的 ui.locale.zhCN 改成 'Chinese (Simplified)',菜单项就会永久停在初始语言。
改成 computed(() => ({ en: t('ui.locale.en'), 'zh-CN': t('ui.locale.zhCN') })) 即可,成本一行。
| // Sync <html lang> from the stored UI locale before paint (mirrors | ||
| // i18n/index.ts detection; screen readers shouldn't see 'en' first). | ||
| try { | ||
| if (localStorage.getItem('fulla-locale') === 'zh-CN') { |
There was a problem hiding this comment.
[MINOR] 注释说 "mirrors i18n/index.ts detection",但它只处理了 localStorage 分支,漏掉 localeFromNavigator()。浏览器语言为 zh、又无存储值时(新用户的常见情形),首屏 HTML 的 <html lang> 是 en,要等 JS 执行才纠正 —— 这正是这段脚本想消除的那类不一致,对屏幕阅读器尤其明显。
建议内联脚本补上 navigator 检测,或改用 vite transformIndexHtml 从共享模块生成这段脚本,避免两处逻辑漂移。user 端 index.html 同样问题。
| // Sync <html lang> from the stored UI locale before paint (mirrors | ||
| // i18n/index.ts detection; screen readers shouldn't see 'en' first). | ||
| try { | ||
| if (localStorage.getItem('fulla-locale') === 'zh-CN') { |
There was a problem hiding this comment.
[MINOR] 同 admin 端:内联 anti-flash 脚本只覆盖 localStorage 分支,未覆盖 localeFromNavigator()。详见 admin/index.html 的同类评论。
| */ | ||
| export function getErrorMessage(code: string, locale: string = DEFAULT_LOCALE): string { | ||
| // Resolve the locale table, falling back to the default language (zh-CN). | ||
| export function getErrorMessage(code: string, locale: string = getCurrentLocale()): string { |
There was a problem hiding this comment.
[NIT] 函数体内 const table = messages[locale] ?? messages[DEFAULT_LOCALE] / table?.[code] 用普通对象做字典查找,未保护原型链。当前 locale 取值受控(services/locale.ts 只产出 'en' | 'zh-CN'),最坏情况是 code='__proto__' 时命中 Object.prototype、再走到 en 的 unknown 兜底,不会崩。
不过 CallbackPage.vue 会把 URL 查询参数 route.query.error 直接当作 code 传进来,且 errorAdapter.ts 的 code 也来自后端响应 —— 用 Object.prototype.hasOwnProperty.call(table, code) 或 Map 更稳妥。messageCatalog.property.test.ts 里已经用了 hasOwnProperty 这个模式,实现里对齐一下即可。
| // Same dynamic-import pattern as crossAppConsistency.property.test.ts; | ||
| // the catalog module is dependency-free so node-env vitest resolves it. | ||
| const adminEn = (await import('../../../admin/src/i18n/en')).en as Tree | ||
| expect(flatten((adminEn.ui ?? {}) as Tree)).toEqual(flatten(en.ui)) |
There was a problem hiding this comment.
[NIT] 前一条 expect(flatten(adminEn.ui)).toEqual(flatten(en.ui)) 被紧随其后的 expect(adminEn.ui).toEqual(en.ui) 完全覆盖,是冗余断言(后者更严格,还能捕获值不同但 key 结构相同的 drift)。建议删掉前一条。
| ref="root" | ||
| class="relative" | ||
| > | ||
| <button |
There was a problem hiding this comment.
[NIT] 下拉菜单缺少 Escape 关闭与方向键导航。role="menu" + role="menuitemradio" 的 ARIA 模式通常期望这两者,目前只能靠点击外部区域关闭。
(onClickOutside 本身实现是对的 —— 按钮在 root 内,点按钮不会误触发关闭。)
…11y, hardening Review dispositions (voidvec's review, 1 MAJOR + 3 MINOR + 4 NIT): - [MAJOR, option A] Error messages resolve once at trigger time; switching locale does not re-translate already-rendered text. Honest wording now in ADR-0013 + i18n guide (en/zh): 'drives page chrome and NEWLY SURFACED error messages', limitation documented, and a dedicated e2e per app locks the snapshot behavior (error -> switch -> still old locale -> retrigger -> new locale). Fully reactive variant (store code, resolve at render, reactive locale) filed as a follow-up issue. - [MINOR] LocaleSwitcher: NATIVE_LABELS is now computed() (t() at setup top-level froze a static snapshot); both byte-synced copies. - [MINOR] index.html inline anti-flash script now mirrors the full detection (stored value wins; else navigator zh* -> zh-CN) — zh-browser first paint no longer announces lang=en. - [NIT] messages/index.ts (both mirrors): own-property lookup guard — codes can come from URL query params (CallbackPage) / backend bodies; '__proto__' must not hit Object.prototype. - [NIT] i18nKeys.test.ts: drop the assertion fully covered by the stricter toEqual that follows it. - [NIT] LocaleSwitcher menu: Escape closes and restores focus to the trigger; ArrowUp/Down cycle through items (ARIA menu pattern). Not changed: email placeholder you@example.com (intentional — example addresses stay untranslated); @intlify/unplugin-vue-i18n precompile (folded into the bundle-budget follow-up). Verified: check-ui-sync 12/12, tsc/build/lint green, vitest 34+4, Playwright user 119/119, admin 186 passed + 6 pre-existing env skips.
|
感谢评审,已全部核实并处置(83fa6a65,验证:sync 12/12、tsc/build/lint、vitest 34+4、Playwright user 119/119 / admin 186+6 既有环境跳过): [MAJOR] 错误消息固化 — 采纳方案 A合并前处理,方案 B 立为 follow-up:ADR-0013 与 i18n guide(en/zh)改为 "drives page chrome and newly surfaced error messages" 并明示局限;两应用各加一条 e2e 显式锁定「先错后切不重译、再触发才跟随」的行为(带 do-not-fix-casually 注记)。完全响应式改造(存 code + 渲染时解析 + 响应式 locale getter 注入,services 层保持零依赖)开为 #158。
[MINOR] NATIVE_LABELS 静态快照 — 已修:改 [MINOR] 内联脚本漏 navigator 分支 — 已修:两应用 index.html 内联脚本补齐完整检测(存储值优先,否则 navigator zh* → zh-CN),zh 浏览器首屏不再先报 lang=en。未采用 transformIndexHtml 生成方案——当前脚本 10 行、注释指向镜像来源,漂移风险可接受。 [NIT] 原型链查找 — 已修: [NIT] i18nKeys 冗余断言 — 已删前一条。 [NIT] 菜单键盘可达性 — 已修:Escape 关闭并归还焦点到触发按钮,ArrowUp/Down 循环聚焦菜单项。 [MINOR] unplugin 预编译 — 同意,与 PR 里注明的 bundle-budget follow-up 合并为 #159(含本次基线数字 user 320 KB / admin 372 KB raw 与验收标准)。 [NIT] email placeholder — 有意为之: |
…0013) - Reject runtime machine-translation widgets (translate.js): page-text egress to third-party clouds, FOUC, terminology drift, offline breakage (evidence in docs/contribute/frontend-i18n.md). - vue-i18n v11 (legacy:false, globalInjection) in both apps; en default + zh-CN; localStorage fulla-locale -> navigator -> en, resolved pre-mount; <html lang> synced incl. inline anti-flash script in index.html. - Services stay dependency-free: active locale travels via services/locale.ts; errorAdapter/getErrorMessage follow the UI locale; DEFAULT_LOCALE flips to the en fallback table; new en error catalog mirrors all ~48 codes (Property 13 now enforced per registered locale). - Extract all user-visible strings: user app 188 leaf keys, admin 306 (en verbatim; the four mixed-Chinese admin spots fixed); nav/option constants become computed; LocaleSwitcher byte-synced across apps; Noto Sans SC added to admin. - Tests: i18nKeys gate (en/zh key parity + call-site key existence + cross-app ui.* parity) via import.meta.glob raw; errorAdapter property updated to en default + explicit zh; e2e zh assertions moved to the en catalog; Playwright pinned to en-US; new i18n.spec per app (switch, persistence, html[lang], zh error via mocked API, bogus-storage fallback). - Docs: ADR-0013 + frontend-i18n guide (en + zh-CN mirrors) + sidebar. Verified: lint 0 errors, tsc, vite build, vitest (user 34 / admin 4), Playwright (user 118/118; admin 185 passed + 6 pre-existing env skips), check-ui-sync 12/12, CJK leftover audit clean, npm ci dry-run, docusaurus build (en + zh-CN).
- License: homepage hero badges (en + zh) and the zh-CN footer still said 'MIT License' after the AGPL-3.0 switch (PR #147); the en footer and LICENSE were already correct. Now AGPL-3.0 everywhere on the site. - Land the working-tree doc sync for the ubuntu 22.04 -> 24.04 base image (Dockerfiles and CI runners already on 24.04): ci-cd-guide (en+zh), deployment guide (en+zh), ci-monitor agent doc. - .gitignore: ignore .env.docker.* (dev/prod docker env split deliverable).
…11y, hardening Review dispositions (voidvec's review, 1 MAJOR + 3 MINOR + 4 NIT): - [MAJOR, option A] Error messages resolve once at trigger time; switching locale does not re-translate already-rendered text. Honest wording now in ADR-0013 + i18n guide (en/zh): 'drives page chrome and NEWLY SURFACED error messages', limitation documented, and a dedicated e2e per app locks the snapshot behavior (error -> switch -> still old locale -> retrigger -> new locale). Fully reactive variant (store code, resolve at render, reactive locale) filed as a follow-up issue. - [MINOR] LocaleSwitcher: NATIVE_LABELS is now computed() (t() at setup top-level froze a static snapshot); both byte-synced copies. - [MINOR] index.html inline anti-flash script now mirrors the full detection (stored value wins; else navigator zh* -> zh-CN) — zh-browser first paint no longer announces lang=en. - [NIT] messages/index.ts (both mirrors): own-property lookup guard — codes can come from URL query params (CallbackPage) / backend bodies; '__proto__' must not hit Object.prototype. - [NIT] i18nKeys.test.ts: drop the assertion fully covered by the stricter toEqual that follows it. - [NIT] LocaleSwitcher menu: Escape closes and restores focus to the trigger; ArrowUp/Down cycle through items (ARIA menu pattern). Not changed: email placeholder you@example.com (intentional — example addresses stay untranslated); @intlify/unplugin-vue-i18n precompile (folded into the bundle-budget follow-up). Verified: check-ui-sync 12/12, tsc/build/lint green, vitest 34+4, Playwright user 119/119, admin 186 passed + 6 pre-existing env skips.
83fa6a6 to
4a41917
Compare
…talogs Rebase integration follow-up: PR #156 (vue-i18n) landed while this branch was in review. The admin-side resolution folded into the rebased commits; this commit moves the USER-portal form onto the same convention (auth.login.passwordChange.* keys, en + zh-CN) instead of the raw English strings, matching the admin side (login.passwordChange.*).
…talogs Rebase integration follow-up: PR #156 (vue-i18n) landed while this branch was in review. The admin-side resolution folded into the rebased commits; this commit moves the USER-portal form onto the same convention (auth.login.passwordChange.* keys, en + zh-CN) instead of the raw English strings, matching the admin side (login.passwordChange.*).
…ation, coverage ratchet gate, signing-key rotation keystore All three ratified by an adversarial re-review on current master (post #156/#157); recommendations A/B/B confirmed unchanged, with #110-C noted as degenerate (key rotation is the last remaining IAM-M1 item, and the repo ships no helm/compose signing-key carrier, so the multi-secret concern was moot). #88-3 (decision A): end_session accepts client_id as the RP identification when id_token_hint is absent (RP-Initiated Logout 1.0 §2.1); the post_logout_redirect_uri must still be registered for that client (same validateRedirectUri gate the aud candidates use — no open redirect; session termination semantics unchanged, and a parameterless end_session already logged out with no proof). With neither hint nor client_id the 400 envelope stands. 3 new integration cases + 2 regressions. #105 (decision B): local coverage ratchet. measure_coverage.py gains --json and --ratchet BASELINE (fail when a non-exempt library drops >0.5pp below baseline; <200-instrumented-line libs exempt; baseline lib missing from the run fails = lost instrumentation; new libs pass until next re-baseline; absent baseline = seed mode printing the JSON). coverage.yml gates the existing job (seconds of added compute). Baseline JSON is committed in a follow-up commit seeded from the first CI run. #110 (decision B): signing-key rotation keystore. JwkManager loads a multi-key store (signing_keystore_dir: <kid>.pem files + active_kid marker), signs with the active kid, verifies by routing on the JWT header kid across all loaded keys (absent kid tries all — RFC 7515 §4.1.4), and publishes EVERY key in JWKS. A configured-but-broken keystore is a hard startup failure (no silent fallback to another key source); the keystore takes precedence over the single-key env/path sources. Rotation is a documented 3-restart procedure (publish → switch → retire; see configuration-guide §9, rewritten from the F-029 to-do). GET /api/admin/oidc/keys now reports the live keystore (keys[] with active/published status) instead of the hardcoded stub; ConfigManager's production key check accepts signing_keystore_dir; endpoint scripts assert the new shape. 7 new keystore unit tests (44/44 in JwkManagerTest). Sync: openapi (end_session client_id param + description, jwks multi-key note, admin keys response) + regenerated openapi.json/Python/Go SDKs; api-diff baseline ratified --force (private-member/static-signature changes with no released consumer); all 8 static gates green; full_test 8/8. Fixes #88 Fixes #105 Fixes #110
…t imports #160 smoke caught a real, latent master break: the frontend-runtime image builds in an isolated context copying ONLY frontends/user/, but tsc (via npm run build) type-checks src tests that dynamically import ../../../admin/** — added in #156 and unbuildable in the container since. No release has shipped an image build since #156, so it went unnoticed. tsconfig.build.json excludes *.test.ts from the build type-check; tests stay type-checked in-repo via the base tsconfig. Admin app is unchanged (its image context is self-contained and its tests keep container type-checking).
…t imports #160 smoke caught a real, latent master break: the frontend-runtime image builds in an isolated context copying ONLY frontends/user/, but tsc (via npm run build) type-checks src tests that dynamically import ../../../admin/** — added in #156 and unbuildable in the container since. No release has shipped an image build since #156, so it went unnoticed. tsconfig.build.json excludes *.test.ts from the build type-check; tests stay type-checked in-repo via the base tsconfig. Admin app is unchanged (its image context is self-contained and its tests keep container type-checking).
… and hooks Consolidates the recurring lessons from the 2026-08/09 engineering sessions (previously only in AI-session memory) into versioned, tool-agnostic assets: - skills: ci-gate-sync (sync-point policies for error codes/endpoints/ migrations/headers), ci-failure-triage (cross-compiler WERROR blind spots, flake taxonomy), release-engineering (six-point + ~15 version carriers, tag recovery, PyPI first publish), pr-workflow (rebase-merge repair, rebase value-loss audit, PAT permission boundary), local-env-runbook (Windows/WSL/Docker/Mimosa/multi-session rules), test-methodology (two test layers, mock injection seam, Playwright pitfalls), and benchmark-methodology (wrk Lua model, A/B discipline, measurement-artifact taxonomy). - rules (path-scoped): sync-points (8-point error-code and 5-point endpoint hard checklists), frontend-contract (verified frontend/backend contract facts), async-cpp-gotchas (traps beyond db-operations: Session::insert no-overwrite, callback double-move, ::drogon:: shadowing). - commands: /preflight (local gate sweep before pushing), /ci-triage (failure classification workflow). - hooks: local-gates.sh (wired to the git-commit PreToolUse hook, replacing the broken full-ctest gate), port-guard.sh, redis-watchdog.ps1. Provenance (source retrospectives): ci-gate-sync/rules.sync-points from PR #115/#141/#149/#157/#179/#180 CI post-mortems; release-engineering from the v1.0.0-v1.1.0 release runs; test-methodology from the coverage push (48.5%->57.2%) and PR #140/#156 e2e work; benchmark-methodology from the four-product comparison campaign; local-env-runbook from environment incident records. AGENTS.md indexes the new rules and skills.
What
Implements frontend multi-language support for both SPAs per ADR-0013: curated message catalogs with vue-i18n v11 (en default + zh-CN), one switcher driving page chrome and error messages. Runtime machine-translation widgets (translate.js) are rejected — evaluation evidence in
docs/contribute/frontend-i18n.md(page-text egress to third-party clouds, FOUC, terminology drift, offline breakage).Key points
services/locale.ts(plain module);errorAdapter/getErrorMessagefollow the UI locale;DEFAULT_LOCALEbecomes the **en fallback table; newen` error catalog mirrors all ~48 codes. Property 13 now enforces coverage per registered locale.computed;LocaleSwitcher.vuebyte-synced across apps (12/12 gate green); Noto Sans SC added to admin.localStorage['fulla-locale']→navigator.languages→ en, resolved synchronously pre-mount;<html lang>synced incl. inline anti-flash script inindex.html.i18nKeys.test.tsper app — en/zh key parity, call-site key existence (import.meta.globraw scan), cross-appui.*parity.en-US; newi18n.spec.tsper app (switch/persistence/html[lang]/zh-error/bogus-storage fallback).docs/contribute/frontend-i18n.mdwith zh-CN mirrors + sidebar entry.Acceptance (full frontend suite, both apps)
Admin's 6 skips are the pre-existing
api-docs.spec.tsconditional skips (backend not running locally) — identical at baseline.Notes for reviewers
DEFAULT_LOCALEitself, which would have bypassed "one switcher drives errors" — fixed via theservices/locale.tsinjection design (node-env unit tests unaffected, no vue-i18n import in mirrored files)./callbacknow maps protocol error codes through the catalog; a rawerror_descriptiononly appears as a secondary detail line when the server sends one (backend-owned string, documented exception).