Skip to content

Feat: Add localization support for admin API and quota UI - #9

Merged
peach0x33a merged 3 commits into
peach0x33a:masterfrom
sstreichan:localization
Sep 17, 2026
Merged

peach0x33a merged 3 commits into
peach0x33a:masterfrom
sstreichan:localization

Conversation

@sstreichan

Copy link
Copy Markdown
Contributor

This pull request updates error handling in the internal/app/admin.go file to provide localized error messages based on the caller's Accept-Language header. The main change is the introduction of the i18n.Message function to translate error messages, and the refactoring of error response functions to support localization throughout the admin API.

The most important changes are:

Localization of Error Responses:

  • All admin API error responses now use the i18n.Message function to provide localized error messages, falling back to English if the requested language is not supported. This improves user experience for non-English speakers.

Refactoring of Error Handling:

  • The writeAdminError function signature is changed to accept the *http.Request object, allowing it to determine the appropriate language for the error message. All calls to writeAdminError throughout the file are updated accordingly. [[1]]

Consistent Error Localization in OAuth Flow:

  • Error responses in the OAuth callback handler are updated to use i18n.Message, ensuring that all user-facing errors in the OAuth flow are localized as well.

These changes collectively ensure that all admin API error messages are ready for localization, improving accessibility and user experience for international users.

@peach0x33a

Copy link
Copy Markdown
Owner

Sorry, there are two local commits that haven’t been pushed yet. Could you please rebase again?

@peach0x33a

peach0x33a commented Sep 15, 2026 •

Copy link
Copy Markdown
Owner

The conflict is exactly one hunk in internal/web/index.html (refreshAllQuotas); internal/app/admin.go auto-merges. But how you resolve it matters — please don't keep your side verbatim.

1. refreshAllQuotas changed contract in 796a990 (landed while this PR was open)

POST /admin/api/quotas/refresh without an id now returns 202 + {started: true, accounts: <number>} and refreshes in the background (quotas.RefreshAllAsync()); the WebUI picks snapshots up on its 5s refreshAll() poll. So:

  1. r.accounts is a number now → your (r.accounts && r.accounts.length) || 0 evaluates to 0 every time. (.length was only correct before 796a990, when the endpoint returned a full account list.)
  2. Drop the trailing refreshAll() — it was removed on purpose: 202 means queued, not done.
  3. Rename the key — quota.refreshed ("Quotas refreshed: {n} account(s)") no longer describes what happens.

Resolved form (keep master's body, keep your t()):

async function refreshAllQuotas() {
  toast(t("quota.refreshing"));
  try {
    const r = await api("/admin/api/quotas/refresh", { method: "POST" });
    // 202 {started, accounts:<n>} — snapshots land via the 5s refreshAll() poll.
    toast(t("quota.refreshStarted", { n: (r && r.accounts) || 0 }));
  } catch (e) { toast(e.message, true); }
}

plus a new key in both dicts in internal/web/index.html:

en:     "quota.refreshStarted": "Started refreshing {n} account(s) — results update automatically",
zh-CN:  "quota.refreshStarted": "已开始刷新 {n} 个账号的额度,结果会自动更新",

Note refreshAccountQuota (the per-account one) is unchanged in master — that endpoint still returns 200 synchronously, so your quota.refreshedOne + refreshAll() there are correct and should stay. Only refreshAllQuotas needs the fix.

2. READMEs were rewritten in the meantime

796a990 / cb8f25a rewrote README.md + README.zh-CN.md. Your PR correctly doesn't touch them — please don't "localize" them while rebasing, it only creates new conflicts.

3. Three paths still leak Chinese into the English UI

Which is this PR's stated goal, so it'd be a shame to leave them:

  • internal/app/admin.go:797 — /admin/api/oauth/status sends err.Error() raw; the WebUI renders it as text at internal/web/index.html:1699, so "授权被取消" / "OAuth 授权超时" still show up in Chinese with an English UI. Wrap it: i18n.Message(i18n.FromRequest(r), err.Error()).
  • internal/app/quota.go:407,491,493 are hardcoded Chinese (API Key 被拒绝(…), 额度接口返回空数据, 所有额度接口均无法访问:…) and reach the UI through quota.last_error / quota.failures (internal/web/index.html:1108-1109). Either make them English and add catalog entries, or map the known causes in the frontend.
  • internal/web/index.html:1109 — failures.join(", ") used to be join(";"); if you're switching the separator, route it through t("common.listSep") so it follows the UI language.

Optional

  • 8 dict keys are never referenced: quota.window.weekly, quota.window.monthly, quota.plan, quota.planStatus, quota.resetIn, time.dayShort, time.hourShort, time.minuteShort.
  • Exact-text matching against errors from accounts.go / clientkeys.go is fragile — one reworded message silently drops the translation. Exported sentinel errors + errors.Is would be sturdier.

For what it's worth, I verified locally that merging your HEAD into current master conflicts only in that one index.html hunk (Go side auto-merges, go test ./... passes afterwards), so the rebase itself is small — items 1 and 3 are the actual work.


Generated by AI

@peach0x33a

Copy link
Copy Markdown
Owner

@sstreichan — heads up before this merges: the branch currently carries two of master's
commits twice, and it can't be cleaned up by a rebase.

While the PR was open I pushed 796a990 (client-IP hardening + quota refresh-all async) and
cb8f25a (README rewrite) to master. In this branch they appear twice:

4b41095  Merge remote-tracking branch 'upstream/master'   ← parents: b972b63 + cb8f25a
├─ b972b63  docs: rewrite both READMEs      author=peach0x33a  committer=Sebastian
├─ 882e578  fix: harden client IP ...       author=peach0x33a  committer=Sebastian
├─ 6339f9d  feat: add localization ...      author=Sebastian
├─ 8fb0471  merge: localize quota UI ...    author=Sebastian
├─ 2aa747f  feat: Add localization ...      author=Xairo
└─ cb8f25a  docs: rewrite both READMEs      author=peach0x33a
   └─ 796a990  fix: harden client IP ...    author=peach0x33a
      └─ 0909635

882e578 / b972b63 are cherry-picked copies of my two commits: the author and the authored
timestamps are mine (2026-09-13), the committer is you (2026-09-16 15:50), which is what
git cherry-pick produces. They were redundant — both commits were already on master, so
the merge alone already brings them in.

The awkward part is that a rebase won't drop them: cb8f25a and b972b63 share a patch-id,
but 882e578 was adapted on top of your 6339f9d, so it no longer matches 796a990. I
tested the usual recovery paths (rebase --onto, --rebase-merges, cherry-picking your
commits onto master) — all conflict, because 2aa747f is based on the much older
ca381de. If this merges as-is, master ends up with those two commits twice.

Not blaming you — the commits landing on master mid-review is what caused it. Just flagging
it before merge rather than after.


Generated by AI

Xairooo and others added 3 commits September 17, 2026 09:26
- Implemented localization for error messages in the admin API, allowing responses to be returned in Simplified Chinese based on the Accept-Language header.
- Created a new package `i18n` to manage translations and language negotiation.
- Added tests to ensure that error messages are correctly localized and that the language negotiation logic functions as expected.
- Introduced helper functions to handle request localization and error message formatting.
Completes the master->localization merge for the quota feature (overview sync card, per-account quota rows, refresh-all button), integrated into the i18n version with all quota UI text routed through t().
- Add quota.* i18n keys (duration, kvExceeded, kvLowBalance, kvLastChecked, exceededBadge, lowBalanceBadge, resetAfter, refreshedOne) to en + zh-CN dicts.
- Localize quota JS (fmtDuration, quotaResetText, quotaBar, quotaMonthBar, quotaDetail, refreshAccountQuota, refreshAllQuotas, quotaSub).
- Fix 4 writeAdminError call sites in admin.go missing *http.Request arg.
Build clean; go test ./... passes.
@sstreichan

Copy link
Copy Markdown
Contributor Author

Thanks for the detailed review and for testing the merge paths — that saved me a lot of time. The history is fixed and force-pushed; details below.

History rebuild

The branch is now a clean linear history of exactly 3 commits on top of current master (cb8f25a), with no duplicated commits:

  1. 2b14bc2 — cherry-pick of my original 2aa747f (Xairo stays the author; the 4 conflict hunks in index.html resolved as master's quota UI + t() routing)
  2. 48cef3a — the quota-UI localization overlay from 8fb0471 (applied via -m 2, so it's now a small focused diff instead of a merge)
  3. 0c9b10a — 6339f9d, plus the async-202 quota.refreshStarted fix that previously lived only in the 4b41095 merge resolution

git diff 4b41095 <new-head> is empty — the final tree is byte-identical to the head you already reviewed, so none of your verification is invalidated. Both duplicate commits are gone; 796a990/cb8f25a now appear once each, as ancestors. go build, go vet, and go test ./... all pass on the rebuilt branch.

Your three leak items — all addressed

  • oauth/status no longer sends raw err.Error(); "authorization canceled: " and "OAuth timed out after " prefixes are in the wrapped table, causes preserved
  • quota.go messages are now English sources with zh-CN entries ("API key rejected: ", "quota endpoints returned no data", "all quota endpoints failed: ")
  • failures.join(t("common.listSep")) — ", " / "、", also reused in the settings restart note

I also confirmed the 8 unused keys you listed are all gone, and ran a parity audit over the dictionary: 187 en keys / 187 zh-CN keys, perfect parity, every t()/data-i18n* usage resolves, zero hardcoded Chinese left outside the dict. All 39 writeAdminError call sites pass the request; the remaining Chinese in non-test Go files is comments and CLI flag help only.

Two small things (non-blocking)

  1. One catalog gap: "quota service unavailable" (admin.go, both 503 sites) has no zh-CN entry, so Chinese users get English for that one message. Fallback works fine — happy to add it in this PR or a follow-up.
  2. Your optional sentinel-errors point: agreed, exact-text matching is the fragile part of this design long-term. I'd suggest filing it as a follow-up issue rather than expanding this PR.

Ready for another look whenever you have time.

@peach0x33a
peach0x33a merged commit 52e5c95 into peach0x33a:master Sep 17, 2026
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.

3 participants