Files
gabrielvidalandClaude Opus 5.5 af80c5bf27 feat(i18n): French leaves the core — a translation kind of plugin
The core speaks English only; every other language is a kind: "translation" plugin
(translation-<lang>; the French one is translation-fr in ai-agent-plugins, seeded once at start).

- plugins: kind translation (typed_manifest.parse_translation: lang, name, englishName, flag,
  locale, promptLine, ui/backend JSON dictionaries — strict, operator-only, in the fingerprint);
  a top-level "languages" field on any plugin (default ["en"]) shown on its page; seeding takes
  translation-*; plugins/translations.py reads the enabled ones (first by id wins a code).
- core/i18n: tr / langs / localized / clean_pref / effective_lang read the installed
  translations; a pick whose translation is gone reads English and is kept; browserLang records
  any base code. core/i18n_fr.py and FRENCH_LINE are gone (language_line = the plugin's promptLine).
- The owner picks a language too (users.json ownerLang, PUT /api/me {lang}; English by default).
- Public GET /api/i18n/languages and /api/i18n/{lang} (ETag/304), guest host and sign-in included.
- Coverage: backend/core/i18n_keys/{ui,backend}.json (kept by the two i18n tests,
  UPDATE_I18N_KEYS=1); a translation's page shows translated / missing / stale / placeholder
  mismatches.
- Frontend: frontend/src/i18n/fr removed; the dictionary comes from the hub, cached in
  localStorage and revalidated in the background (first boot in a language waits <= 4 s, any
  failure is English); Lang is a string; number/currency style from the translation's locale;
  LanguageSelect lists English + installed translations (hidden when none); Settings → Plugins
  has a Translations kind (tab, catalog filter, group) and a Translation section with the
  missing-strings count; mock is English only.
- Tests: test_i18n.py rewritten on a made-up translation; i18n_testkit.speaking() for the
  tests that need a second language. authz golden, openapi.json + src/generated regenerated;
  docs/plugins.md (Translations), CLAUDE.md, i18n README, docs/settings.md.

Changelog
- Added: languages are plugins — Settings → Plugins → Translations; the owner can pick a language.
- Changed: French moved to the translation-fr plugin (seeded at start: nothing changes for guests).
- Removed: the core's built-in French dictionaries.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 19:07:22 +01:00

158 lines
6.1 KiB
Python

"""
The backend's languages: the text the app itself sends a person — the
sign-in mail, its own pushes, the API errors a guest can hit, the *New
project* form. The core speaks **English only**; every other language is a
translation plugin (``kind: "translation"``, ``translation-<lang>`` —
``plugins/translations.py``), whose ``backend`` dictionary this module reads.
The frontend's half is ``frontend/src/i18n/``.
* ``tr(lang, "Hi {name},", name=…)`` — the English text **is the key**. A
missing entry, ``lang`` "en", or a language no enabled translation speaks
falls back to the English, placeholders filled either way. ``{var}``
placeholders only: a brace that isn't one (code in a string) stays.
* ``msg("…")`` — marks a string that reaches :func:`tr` through a variable
(a table of labels), so ``test_i18n.py`` still sees it.
* A person's language (``users.json`` → ``lang``; the owner's own pick in
the same file): ``auto`` | ``en`` | an installed code, ``auto`` being their
browser's — the primary ``Accept-Language`` recorded as ``browserLang``
when they sign in and on ``GET /api/me``. :func:`effective_lang` resolves
it; a stored pick whose translation is gone reads English and is kept.
Text written *for Claude* (system prompts, app turns, notes appended to a
prompt) stays English; a run of a person reading another language gets the
translation's prompt line (``users/runs.language_line``).
"""
from __future__ import annotations
import re
DEFAULT_LANG = "en"
# The shape of a language code a preference may name (stored as picked even
# when no translation speaks it yet — it reads English until one does).
_CODE_RE = re.compile(r"^[a-z]{2,3}$")
_VAR_RE = re.compile(r"\{(\w+)\}")
def _translations():
from plugins.translations import current
return current()
def langs() -> tuple[str, ...]:
"""English, then every language an enabled translation speaks."""
return (DEFAULT_LANG, *_translations().codes())
def lang_prefs() -> tuple[str, ...]:
"""What a person may pick: ``auto``, English or an installed language."""
return ("auto", *langs())
def msg(english: str) -> str:
"""A string translated later through a variable: ``tr(lang, LABELS[k])``."""
return english
def tr(lang: str | None, english: str, **vars) -> str:
"""``english`` in ``lang`` with its ``{var}`` placeholders filled."""
text = english
if lang and lang != DEFAULT_LANG:
t = _translations().get(lang)
if t is not None:
text = t.backend.get(english, english)
if not vars:
return text
return _VAR_RE.sub(lambda m: str(vars[m.group(1)]) if m.group(1) in vars
else m.group(0), text)
def localized(build) -> dict:
"""``{lang: build(lang)}`` for every installed language but English —
the per-recipient variants a shared notice carries (``i18n`` on a push:
``{"<lang>": {"title", "message"}}``; the English is ``build("en")``)."""
return {lang: build(lang) for lang in langs() if lang != DEFAULT_LANG}
def pick(variants: dict | None, lang: str | None) -> dict | None:
"""The variant of a notice for ``lang``, None ⇒ keep the English."""
if not variants or not lang or lang == DEFAULT_LANG:
return None
v = variants.get(lang)
return v if isinstance(v, dict) else None
def clean_pref(value) -> str:
"""A language preference as stored: ``auto``, ``en`` or a language an
enabled translation speaks; ValueError for anything else."""
v = str(value or "").strip().lower()
prefs = lang_prefs()
if v not in prefs:
raise ValueError(f"lang must be one of {', '.join(prefs)}")
return v
def is_code(value) -> bool:
"""A plausible base language code (``fr``, ``de``) — installed or not."""
return isinstance(value, str) and bool(_CODE_RE.match(value))
def browser_lang(accept_language: str | None) -> str | None:
"""The browser's first-choice base language from an ``Accept-Language``
header, whatever it is (``de`` too) — None when there is none."""
best, best_q = None, -1.0
for part in (accept_language or "").split(","):
tag, _, params = part.strip().partition(";")
tag = tag.strip().lower()
if not tag or tag == "*":
continue
q = 1.0
for p in params.split(";"):
k, _, val = p.strip().partition("=")
if k.strip() == "q":
try:
q = float(val)
except ValueError:
q = 0.0
if q > best_q:
best, best_q = tag.split("-")[0], q
return best if is_code(best) else None
def primary_lang(accept_language: str | None) -> str | None:
""":func:`browser_lang` when the app speaks it (English or an installed
translation), else None."""
best = browser_lang(accept_language)
return best if best in langs() else None
def effective_lang(user: dict | None, accept_language: str | None = None) -> str:
"""The language the app speaks to ``user``: their ``lang`` when it is
English or installed (another stored pick — its translation removed —
reads English); for ``auto`` the browser language last recorded for them
(``browserLang``) when the app speaks it; else this request's
``Accept-Language``; else English."""
u = user or {}
installed = langs()
pref = u.get("lang")
if pref and pref != "auto":
return pref if pref in installed else DEFAULT_LANG
if u.get("browserLang") in installed:
return u["browserLang"]
return primary_lang(accept_language) or DEFAULT_LANG
def locale_of(lang: str | None) -> str | None:
"""The BCP 47 locale of an installed language (None for English)."""
t = _translations().get(lang) if lang and lang != DEFAULT_LANG else None
return t.locale if t is not None else None
def prompt_line(lang: str | None, name: str) -> str | None:
"""The translation's system-prompt line for a person reading ``lang``
(``{name}`` = theirs), None for English or a language without one."""
t = _translations().get(lang) if lang and lang != DEFAULT_LANG else None
if t is None or not t.prompt_line:
return None
return t.prompt_line.replace("{name}", name)