Files
ai-agent/backend/plugins/translations.py
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

195 lines
7.1 KiB
Python

"""The installed translations: the owner's enabled ``kind: "translation"``
plugins (``translation-<lang>``), each one language for the whole app.
The core speaks English only. A translation plugin brings the rest
(``plugins/typed_manifest.parse_translation``): its own name and flag, the
BCP 47 locale numbers and dates follow, the system-prompt line a run of a
person reading it gets, and two dictionaries keyed by the English text —
``ui`` (the PWA's ``t()`` strings, served to browsers by
``GET /api/i18n/{lang}``) and ``backend`` (what :func:`core.i18n.tr` sends:
mails, pushes, API errors).
One plugin per language: when two enabled plugins claim the same code, the
first by id keeps it. :func:`current` is what everyone reads — a
:class:`Translations` set rebuilt when the plugin store's version moves or a
dictionary file changes on disk (checked at most every few seconds), never
per call.
The core also keeps the lists of its English keys (``core/i18n_keys/ui.json``
from ``frontend/src/i18n/i18n.test.tsx``, ``backend.json`` from
``test_i18n.py`` — ``UPDATE_I18N_KEYS=1`` rewrites them) so a translation's
page can say how many it is missing (:func:`coverage`).
"""
from __future__ import annotations
import hashlib
import json
import logging
import pathlib
import re
import threading
import time
from dataclasses import dataclass, field
from typing import Any
log = logging.getLogger(__name__)
KEYS_DIR = pathlib.Path(__file__).resolve().parent.parent / "core" / "i18n_keys"
_RECHECK_S = 5.0
_VAR_RE = re.compile(r"\{(\w+)\}")
@dataclass(frozen=True)
class Translation:
lang: str
plugin_id: str
name: str
english_name: str
flag: str | None
locale: str
prompt_line: str | None
ui: dict[str, str] = field(default_factory=dict)
backend: dict[str, str] = field(default_factory=dict)
etag: str = ""
languages: tuple[str, ...] = ()
def public(self) -> dict[str, Any]:
"""What a browser may know about it (``GET /api/i18n/languages``)."""
return {"code": self.lang, "name": self.name, "englishName": self.english_name,
"flag": self.flag, "locale": self.locale, "etag": self.etag}
class Translations:
"""The enabled translations by code (first plugin by id wins a code)."""
def __init__(self, items: list[Translation], version: Any = None):
self.version = version
self.by_lang: dict[str, Translation] = {}
for t in items:
self.by_lang.setdefault(t.lang, t)
def codes(self) -> tuple[str, ...]:
return tuple(self.by_lang)
def get(self, lang: str | None) -> Translation | None:
return self.by_lang.get(lang or "")
_EMPTY = Translations([])
_lock = threading.Lock()
_store = None
_cache: tuple[Any, float, Translations] | None = None # (key, checked at, set)
def bind(store) -> None:
"""Read translations from this plugin store (``core/state.build_state``)."""
global _store, _cache
with _lock:
_store, _cache = store, None
def _files(rec: dict) -> list[pathlib.Path]:
tv = (rec.get("manifest") or {}).get("translation") or {}
root = pathlib.Path(rec.get("dir") or "")
return [root / tv[k] for k in ("ui", "backend") if tv.get(k)]
def _mtimes(recs: list[dict]) -> tuple:
out = []
for r in recs:
for f in _files(r):
try:
st = f.stat()
out.append((str(f), st.st_mtime_ns, st.st_size))
except OSError:
out.append((str(f), 0, 0))
return tuple(out)
def _load(rec: dict) -> Translation | None:
from plugins.typed_manifest import load_dictionary
mf = rec.get("manifest") or {}
tv = mf.get("translation") or {}
if not tv.get("lang"):
return None
root = pathlib.Path(rec.get("dir") or "")
dicts: dict[str, dict[str, str]] = {}
for key in ("ui", "backend"):
errors: list[str] = []
dicts[key] = load_dictionary(root / tv[key], f"{rec['id']} {key}", errors) if tv.get(key) else {}
if errors:
log.warning("translation %s: %s", rec["id"], "; ".join(errors[:3]))
# the UI dictionary's ETag: what a browser revalidates its copy against
body = json.dumps(dicts["ui"], ensure_ascii=False, sort_keys=True).encode()
return Translation(
lang=tv["lang"], plugin_id=rec["id"], name=tv.get("name") or tv["lang"],
english_name=tv.get("englishName") or tv.get("name") or tv["lang"],
flag=tv.get("flag"), locale=tv.get("locale") or tv["lang"],
prompt_line=tv.get("promptLine"), ui=dicts["ui"], backend=dicts["backend"],
etag=hashlib.sha256(body).hexdigest()[:20],
languages=tuple(mf.get("languages") or ("en",)))
def current() -> Translations:
"""The enabled translations now (an empty set without a store)."""
global _cache
store = _store
if store is None:
return _EMPTY
now = time.monotonic()
c = _cache
if c is not None and c[0][0] == store.version and now - c[1] < _RECHECK_S:
return c[2]
try:
recs = store.active_by_kind("translation")
except Exception: # noqa: BLE001 — a broken store speaks English
log.exception("reading the translation plugins failed")
return _EMPTY
key = (store.version, _mtimes(recs))
with _lock:
if _cache is not None and _cache[0] == key:
_cache = (key, now, _cache[2])
return _cache[2]
items = [t for t in (_load(r) for r in recs) if t is not None]
_cache = (key, now, Translations(items, key))
return _cache[2]
# ── coverage: what a translation is missing against the core's English ─────
def core_keys() -> dict[str, list[str]]:
"""The core's English keys: ``{"ui": [...], "backend": [...]}``."""
out: dict[str, list[str]] = {}
for k in ("ui", "backend"):
try:
data = json.loads((KEYS_DIR / f"{k}.json").read_text(encoding="utf-8"))
out[k] = [x for x in data if isinstance(x, str)] if isinstance(data, list) else []
except (OSError, ValueError):
out[k] = []
return out
def _placeholders(s: str) -> list[str]:
return sorted(_VAR_RE.findall(s))
def coverage(t: Translation) -> dict[str, Any]:
"""Per dictionary: how many of the core's keys it has, which are missing
(the first 50), which entries the core no longer uses, and the entries
whose ``{placeholders}`` differ from the English."""
keys = core_keys()
out: dict[str, Any] = {}
for part, d in (("ui", t.ui), ("backend", t.backend)):
want = keys[part]
wanted = set(want)
missing = [k for k in want if k not in d]
# a context key (``verb|Open``) compares the text after the bar
bad = [k for k, v in d.items()
if _placeholders(re.sub(r"^[^|{]*\|", "", k)) != _placeholders(v)]
out[part] = {"total": len(want), "translated": len(want) - len(missing),
"missing": len(missing), "missingSample": missing[:50],
"stale": len([k for k in d if k not in wanted]),
"placeholderMismatch": bad[:50]}
out["missing"] = out["ui"]["missing"] + out["backend"]["missing"]
return out