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>
513 lines
26 KiB
Python
513 lines
26 KiB
Python
"""The backend's languages (core/i18n.py + plugins/translations.py): English
|
|
in the core, every other language a ``translation-<lang>`` plugin — the
|
|
``tr`` helper and the list of English keys it is checked against, a person's
|
|
``lang`` / ``browserLang`` and the API around them, the public ``/api/i18n``
|
|
routes, the guest-facing text that follows the language, and who may install
|
|
a translation.
|
|
|
|
The translation here is a made-up one, **Zedish** (``zz``), installed from a
|
|
throw-away folder: each entry is the English wrapped in ``⟦…⟧``, so a test
|
|
sees at once whether a text went through it. The real French lives in the
|
|
plugins repo (``translation-fr``), whose own test checks it against
|
|
``core/i18n_keys/``.
|
|
|
|
Imports ``main`` against throwaway paths (no startup event → no threads)."""
|
|
|
|
import ast
|
|
import json
|
|
import os
|
|
import pathlib
|
|
import re
|
|
import tempfile
|
|
import unittest
|
|
|
|
TMP = pathlib.Path(tempfile.mkdtemp())
|
|
for k, v in {"DB_PATH": TMP / "x.db", "TRANSCRIPTS_DIR": TMP / "t",
|
|
"WORKSPACE": TMP, "REPO_DIR": TMP, "ARCHIVE_DIR": TMP / "arch",
|
|
"META_PATH": TMP / "meta.json", "WORKERS_PATH": TMP / "w.json",
|
|
"PROFILES_PATH": TMP / "profiles.json",
|
|
"WORKERS_TRANSCRIPTS_DIR": TMP / "mirror",
|
|
"CRON_PATH": TMP / "cron.json", "NOTIFY_PATH": TMP / "n.json",
|
|
"FORMS_PATH": TMP / "f.json", "UI_STATE_PATH": TMP / "ui.json",
|
|
"NOTIF_READ_PATH": TMP / "nr.json",
|
|
"MAIL_TRIGGER_SENDERS_PATH": TMP / "mt.json",
|
|
"USERS_PATH": TMP / "users.json", "AUTH_PATH": TMP / "auth.json",
|
|
"PROJECTS_DIR": TMP / "projects", "PLUGINS_DIR": TMP / "plugins",
|
|
"INTERNAL_API_TOKEN": "tok", "GUEST_HOSTS": "claude.example.test",
|
|
"SIDECAR_TOKEN": "", "PI_TRANSCRIPTS_DIR": ""}.items():
|
|
os.environ[k] = str(v)
|
|
(TMP / "projects" / "film").mkdir(parents=True)
|
|
|
|
from fastapi.testclient import TestClient # noqa: E402
|
|
|
|
import main # noqa: E402
|
|
import runs.routes as run_routes # noqa: E402
|
|
from core.i18n import (browser_lang, effective_lang, langs, localized, # noqa: E402
|
|
pick, primary_lang, tr)
|
|
from plugins import translations # noqa: E402
|
|
from plugins.manifest import ManifestError, validate_manifest # noqa: E402
|
|
from plugins.store import OWNER_UID # noqa: E402
|
|
from users import deliver, mailer # noqa: E402
|
|
from users import runs as guest_runs # noqa: E402
|
|
from users.caller import OWNER, SESSION_COOKIE, guest_from_record # noqa: E402
|
|
|
|
DEPS = main.app.state.ai
|
|
OWNER_H = {"X-Internal-Auth": "tok"}
|
|
BACKEND = pathlib.Path(__file__).resolve().parent
|
|
KEYS = BACKEND / "core" / "i18n_keys"
|
|
|
|
|
|
def _literals() -> dict[str, str]:
|
|
"""Every ``tr(lang, "…")`` / ``msg("…")`` literal in the backend → where."""
|
|
out: dict[str, str] = {}
|
|
for f in sorted(BACKEND.rglob("*.py")):
|
|
if f.name.startswith("test_") or "__pycache__" in f.parts:
|
|
continue
|
|
for n in ast.walk(ast.parse(f.read_text(encoding="utf-8"), str(f))):
|
|
if not isinstance(n, ast.Call):
|
|
continue
|
|
fn = n.func.id if isinstance(n.func, ast.Name) else getattr(n.func, "attr", "")
|
|
arg = (n.args[1] if fn == "tr" and len(n.args) > 1
|
|
else n.args[0] if fn == "msg" and n.args else None)
|
|
if isinstance(arg, ast.Constant) and isinstance(arg.value, str):
|
|
out.setdefault(arg.value, f"{f.relative_to(BACKEND)}:{n.lineno}")
|
|
return out
|
|
|
|
|
|
def zz(english: str) -> str:
|
|
return f"⟦{english}⟧"
|
|
|
|
|
|
ZZ_LINE = "- **Language: {name} reads Zedish.** Write to them in Zedish."
|
|
|
|
|
|
def make_translation(root: pathlib.Path, lang: str = "zz", *, ui=None, backend=None,
|
|
name: str = "Zedish") -> pathlib.Path:
|
|
"""A translation plugin folder: ``translation-<lang>``, every core key
|
|
``⟦wrapped⟧`` unless dictionaries are given."""
|
|
d = root / f"translation-{lang}"
|
|
(d / "i18n").mkdir(parents=True, exist_ok=True)
|
|
keys = translations.core_keys()
|
|
(d / "i18n" / "ui.json").write_text(json.dumps(
|
|
ui if ui is not None else {k: zz(k) for k in keys["ui"]}), encoding="utf-8")
|
|
(d / "i18n" / "backend.json").write_text(json.dumps(
|
|
backend if backend is not None else {k: zz(k) for k in _literals()}), encoding="utf-8")
|
|
(d / "plugin.json").write_text(json.dumps({
|
|
"schema": 1, "id": f"translation-{lang}", "name": name, "version": "1.0.0",
|
|
"kind": "translation", "description": "test", "icon": "languages",
|
|
"translation": {"lang": lang, "name": name, "englishName": "Zedish", "flag": "🏳️",
|
|
"locale": f"{lang}-ZZ", "promptLine": ZZ_LINE,
|
|
"ui": "i18n/ui.json", "backend": "i18n/backend.json"}}), encoding="utf-8")
|
|
return d
|
|
|
|
|
|
PLUGIN_DIR = make_translation(TMP / "src")
|
|
|
|
|
|
def install_zz() -> None:
|
|
if not any(r["id"] == "translation-zz" for r in DEPS.plugin_store.list_for(OWNER_UID)):
|
|
DEPS.plugin_store.install(OWNER_UID, str(PLUGIN_DIR), is_owner=True, approve=True)
|
|
DEPS.plugin_store.update(OWNER_UID, "translation-zz", enabled=True)
|
|
|
|
|
|
def uninstall_zz() -> None:
|
|
if any(r["id"] == "translation-zz" for r in DEPS.plugin_store.list_for(OWNER_UID)):
|
|
DEPS.plugin_store.uninstall(OWNER_UID, "translation-zz")
|
|
|
|
|
|
install_zz()
|
|
|
|
|
|
class Keys(unittest.TestCase):
|
|
def test_backend_keys_list_is_in_step(self):
|
|
"""``core/i18n_keys/backend.json`` is every ``tr``/``msg`` literal
|
|
(``UPDATE_I18N_KEYS=1`` rewrites it) — what a translation's page and
|
|
the plugins repo's test count its missing entries against."""
|
|
want = json.dumps(sorted(_literals()), indent=1, ensure_ascii=False) + "\n"
|
|
path = KEYS / "backend.json"
|
|
if os.environ.get("UPDATE_I18N_KEYS"):
|
|
path.write_text(want, encoding="utf-8")
|
|
self.assertEqual(path.read_text(encoding="utf-8"), want,
|
|
"run UPDATE_I18N_KEYS=1 python -m pytest test_i18n.py")
|
|
|
|
def test_the_ui_keys_list_exists(self):
|
|
keys = translations.core_keys()
|
|
self.assertGreater(len(keys["ui"]), 100)
|
|
self.assertIn("Sign in", keys["ui"])
|
|
|
|
def test_core_has_no_dictionary_of_its_own(self):
|
|
self.assertFalse((BACKEND / "core" / "i18n_fr.py").exists())
|
|
src = (BACKEND / "core" / "i18n.py").read_text(encoding="utf-8")
|
|
self.assertNotIn('"fr"', src)
|
|
|
|
|
|
class Tr(unittest.TestCase):
|
|
def setUp(self):
|
|
install_zz()
|
|
|
|
def test_english_is_the_key(self):
|
|
self.assertEqual(tr("en", "login required"), "login required")
|
|
self.assertEqual(tr("zz", "login required"), zz("login required"))
|
|
|
|
def test_missing_entry_or_language_falls_back_to_english(self):
|
|
self.assertEqual(tr("zz", "nobody translated {thing}", thing="this"),
|
|
"nobody translated this")
|
|
for lang in (None, "", "de", "auto", "fr"):
|
|
self.assertEqual(tr(lang, "login required"), "login required")
|
|
|
|
def test_placeholders(self):
|
|
self.assertEqual(tr("zz", "Hi {name},", name="Dom"), zz("Hi Dom,"))
|
|
self.assertEqual(tr("en", "{n} days", n=3), "3 days")
|
|
# a brace that isn't a placeholder (or a var not passed) stays as is
|
|
self.assertEqual(tr("en", "run `{a}` with {b} {c}", b="x"), "run `{a}` with x {c}")
|
|
|
|
def test_langs_follow_the_installed_translations(self):
|
|
self.assertEqual(langs(), ("en", "zz"))
|
|
DEPS.plugin_store.update(OWNER_UID, "translation-zz", enabled=False)
|
|
try:
|
|
self.assertEqual(langs(), ("en",))
|
|
self.assertEqual(tr("zz", "login required"), "login required")
|
|
self.assertEqual(localized(lambda lang: lang), {})
|
|
finally:
|
|
install_zz()
|
|
|
|
def test_localized_and_pick(self):
|
|
v = localized(lambda lang: {"title": tr(lang, "Tap to answer")})
|
|
self.assertEqual(v, {"zz": {"title": zz("Tap to answer")}})
|
|
self.assertEqual(pick(v, "zz"), {"title": zz("Tap to answer")})
|
|
self.assertIsNone(pick(v, "en"))
|
|
self.assertIsNone(pick(None, "zz"))
|
|
|
|
def test_coverage(self):
|
|
t = translations.current().get("zz")
|
|
cov = translations.coverage(t)
|
|
self.assertEqual(cov["missing"], 0)
|
|
self.assertEqual(cov["ui"]["translated"], cov["ui"]["total"])
|
|
# one missing, one stale, one with other placeholders
|
|
keys = translations.core_keys()
|
|
ui = {k: zz(k) for k in keys["ui"][1:]}
|
|
ui["Gone {x}"] = "⟦Gone⟧"
|
|
part = translations.coverage(translations.Translation(
|
|
lang="zz", plugin_id="x", name="", english_name="", flag=None, locale="zz",
|
|
prompt_line=None, ui=ui, backend={}))["ui"]
|
|
self.assertEqual((part["missing"], part["stale"], part["placeholderMismatch"]),
|
|
(1, 1, ["Gone {x}"]))
|
|
self.assertEqual(part["missingSample"], [keys["ui"][0]])
|
|
|
|
|
|
class Manifest(unittest.TestCase):
|
|
def test_a_valid_translation(self):
|
|
mf = validate_manifest(PLUGIN_DIR)
|
|
self.assertEqual(mf["kind"], "translation")
|
|
self.assertEqual(mf["languages"], ["en", "zz"])
|
|
self.assertEqual(mf["translation"]["locale"], "zz-ZZ")
|
|
|
|
def test_strict(self):
|
|
def bad(**patch):
|
|
d = make_translation(pathlib.Path(tempfile.mkdtemp()))
|
|
raw = json.loads((d / "plugin.json").read_text())
|
|
for k, v in patch.items():
|
|
if k == "translation":
|
|
raw["translation"].update(v)
|
|
else:
|
|
raw[k] = v
|
|
(d / "plugin.json").write_text(json.dumps(raw))
|
|
with self.assertRaises(ManifestError) as e:
|
|
validate_manifest(d)
|
|
return str(e.exception)
|
|
self.assertIn("translation-zz", bad(id="lang-zz"))
|
|
self.assertIn("English", bad(translation={"lang": "en"}))
|
|
self.assertIn("unknown keys", bad(translation={"extra": 1}))
|
|
self.assertIn("locale", bad(translation={"locale": "de-DE"}))
|
|
self.assertIn("'..'", bad(translation={"ui": "../../etc/passwd.json"}))
|
|
self.assertIn("languages[0]", bad(languages=["French"]))
|
|
self.assertIn("only allowed on kind", bad(kind="app"))
|
|
|
|
def test_languages_on_an_app_plugin(self):
|
|
from plugins.manifest import _languages
|
|
self.assertEqual(_languages(None, []), ["en"])
|
|
self.assertEqual(_languages(["fr", "en", "fr"], []), ["en", "fr"])
|
|
|
|
def test_only_the_operator_installs_one(self):
|
|
from plugins.manifest import requires_operator
|
|
self.assertTrue(requires_operator(validate_manifest(PLUGIN_DIR)))
|
|
|
|
|
|
class Lang(unittest.TestCase):
|
|
def setUp(self):
|
|
install_zz()
|
|
|
|
def test_primary_language_of_a_header(self):
|
|
self.assertEqual(primary_lang("zz-ZZ,zz;q=0.9,en-US;q=0.8,en;q=0.7"), "zz")
|
|
self.assertEqual(primary_lang("en-GB"), "en")
|
|
self.assertEqual(primary_lang("en;q=0.5, zz;q=0.9"), "zz")
|
|
self.assertIsNone(primary_lang("de-DE,en;q=0.5")) # another first choice
|
|
self.assertEqual(browser_lang("de-DE,en;q=0.5"), "de") # recorded all the same
|
|
self.assertIsNone(primary_lang(""))
|
|
self.assertIsNone(primary_lang(None))
|
|
self.assertIsNone(primary_lang("*"))
|
|
|
|
def test_effective_language(self):
|
|
self.assertEqual(effective_lang({"lang": "zz", "browserLang": "en"}), "zz")
|
|
self.assertEqual(effective_lang({"lang": "auto", "browserLang": "zz"}, "en"), "zz")
|
|
self.assertEqual(effective_lang({"lang": "auto"}, "zz-ZZ,zz"), "zz")
|
|
self.assertEqual(effective_lang({}, "de"), "en")
|
|
self.assertEqual(effective_lang(None), "en")
|
|
# a pick whose translation is gone reads English (and is kept)
|
|
self.assertEqual(effective_lang({"lang": "fr", "browserLang": "zz"}), "en")
|
|
|
|
|
|
class Users(unittest.TestCase):
|
|
def setUp(self):
|
|
install_zz()
|
|
for u in DEPS.users.all():
|
|
DEPS.users.delete(u["id"])
|
|
self.dom = DEPS.users.create("dom@example.com", "Dom", projects={"film": "chat"},
|
|
models=["sonnet"])
|
|
self.cookie = DEPS.auth.open_session(self.dom["id"])
|
|
|
|
def guest(self, lang_header="zz-ZZ,zz;q=0.9"):
|
|
c = TestClient(main.app, base_url="https://claude.example.test",
|
|
headers={"Accept-Language": lang_header,
|
|
"Origin": "https://claude.example.test"})
|
|
c.cookies.set(SESSION_COOKIE, self.cookie)
|
|
return c
|
|
|
|
# ── the store ────────────────────────────────────────────────────────────
|
|
def test_store_lang_field(self):
|
|
self.assertEqual(self.dom["lang"], "auto")
|
|
self.assertEqual(DEPS.users.update("dom", {"lang": "ZZ"})["lang"], "zz")
|
|
with self.assertRaises(ValueError):
|
|
DEPS.users.update("dom", {"lang": "de"}) # no translation for it
|
|
self.assertEqual(DEPS.users.get("dom")["lang"], "zz")
|
|
|
|
def test_a_pick_outlives_its_translation(self):
|
|
DEPS.users.update("dom", {"lang": "zz"})
|
|
DEPS.plugin_store.update(OWNER_UID, "translation-zz", enabled=False)
|
|
try:
|
|
self.assertEqual(DEPS.users.get("dom")["lang"], "zz") # kept
|
|
self.assertEqual(DEPS.users.lang_of("dom"), "en") # reads English
|
|
finally:
|
|
install_zz()
|
|
self.assertEqual(DEPS.users.lang_of("dom"), "zz")
|
|
|
|
def test_browser_language_written_only_when_it_changes(self):
|
|
self.assertTrue(DEPS.users.set_browser_lang("dom", "zz"))
|
|
self.assertFalse(DEPS.users.set_browser_lang("dom", "zz"))
|
|
self.assertFalse(DEPS.users.set_browser_lang("dom", "not a code"))
|
|
self.assertFalse(DEPS.users.set_browser_lang("dom", None))
|
|
self.assertEqual(DEPS.users.get("dom")["browserLang"], "zz")
|
|
self.assertEqual(DEPS.users.lang_of("dom"), "zz")
|
|
DEPS.users.update("dom", {"lang": "en"})
|
|
self.assertEqual(DEPS.users.lang_of("dom"), "en")
|
|
|
|
# ── the API ──────────────────────────────────────────────────────────────
|
|
def test_me_carries_lang_and_records_the_browser(self):
|
|
r = self.guest().get("/api/me")
|
|
self.assertEqual(r.status_code, 200, r.text)
|
|
self.assertEqual(r.json()["lang"], "auto")
|
|
self.assertEqual(DEPS.users.get("dom")["browserLang"], "zz")
|
|
r = self.guest().put("/api/me", json={"lang": "en"})
|
|
self.assertEqual((r.status_code, r.json()["lang"]), (200, "en"), r.text)
|
|
r = self.guest().put("/api/me", json={"lang": "klingon"})
|
|
self.assertEqual(r.status_code, 400, r.text)
|
|
self.assertEqual(DEPS.users.get("dom")["lang"], "en")
|
|
|
|
def test_the_owner_picks_a_language_english_by_default(self):
|
|
c = TestClient(main.app)
|
|
self.assertEqual(c.get("/api/me", headers=OWNER_H).json()["lang"], "en")
|
|
r = c.put("/api/me", json={"lang": "zz"}, headers=OWNER_H)
|
|
self.assertEqual((r.status_code, r.json()["lang"]), (200, "zz"), r.text)
|
|
self.assertEqual(c.put("/api/me", json={"lang": "de"}, headers=OWNER_H).status_code, 400)
|
|
self.assertEqual(c.put("/api/me", json={"name": "x"}, headers=OWNER_H).status_code, 400)
|
|
self.assertEqual(c.get("/api/me", headers=OWNER_H).json()["lang"], "zz")
|
|
self.assertEqual(c.put("/api/me", json={"lang": "en"}, headers=OWNER_H).json()["lang"], "en")
|
|
|
|
def test_owner_sets_a_guests_language(self):
|
|
c = TestClient(main.app)
|
|
r = c.put("/api/users/dom", json={"lang": "zz"}, headers=OWNER_H)
|
|
self.assertEqual((r.status_code, r.json()["lang"]), (200, "zz"), r.text)
|
|
self.assertEqual(c.put("/api/users/dom", json={"lang": "xx"},
|
|
headers=OWNER_H).status_code, 400)
|
|
DEPS.users.set_browser_lang("dom", "en")
|
|
row = next(u for u in c.get("/api/users", headers=OWNER_H).json()["users"]
|
|
if u["id"] == "dom")
|
|
self.assertEqual((row["lang"], row["browserLang"]), ("zz", "en"))
|
|
|
|
def test_login_records_the_browser_and_answers_in_its_language(self):
|
|
c = TestClient(main.app, base_url="https://claude.example.test",
|
|
headers={"Accept-Language": "zz-ZZ"})
|
|
r = c.post("/api/auth/login", json={"token": "nope"})
|
|
self.assertEqual(r.status_code, 401)
|
|
self.assertEqual(r.json()["detail"], {"message": zz("this link is invalid or expired"),
|
|
"kind": "link_invalid"})
|
|
token = DEPS.auth.mint_link("dom")
|
|
self.assertEqual(c.post("/api/auth/login", json={"token": token}).status_code, 200)
|
|
self.assertEqual(DEPS.users.get("dom")["browserLang"], "zz")
|
|
|
|
# ── the public routes ────────────────────────────────────────────────────
|
|
def test_languages_and_dictionary_answer_without_a_session(self):
|
|
# the guest host signed out, and the admin host (the owner, through
|
|
# Authelia — here the host token)
|
|
for c in (TestClient(main.app, base_url="https://claude.example.test"),
|
|
TestClient(main.app, headers=OWNER_H)):
|
|
r = c.get("/api/i18n/languages")
|
|
self.assertEqual(r.status_code, 200, r.text)
|
|
langs_ = r.json()["languages"]
|
|
self.assertEqual([x["code"] for x in langs_], ["zz"])
|
|
self.assertEqual((langs_[0]["name"], langs_[0]["locale"]), ("Zedish", "zz-ZZ"))
|
|
r = c.get("/api/i18n/zz")
|
|
self.assertEqual(r.status_code, 200, r.text)
|
|
self.assertEqual(r.json()["Sign in"], zz("Sign in"))
|
|
etag = r.headers["etag"]
|
|
self.assertEqual(etag.strip('"'), langs_[0]["etag"])
|
|
self.assertEqual(c.get("/api/i18n/zz", headers={"If-None-Match": etag}).status_code, 304)
|
|
self.assertEqual(c.get("/api/i18n/fr").status_code, 404)
|
|
|
|
def test_no_translation_no_languages(self):
|
|
DEPS.plugin_store.update(OWNER_UID, "translation-zz", enabled=False)
|
|
try:
|
|
r = TestClient(main.app, base_url="https://claude.example.test").get("/api/i18n/languages")
|
|
self.assertEqual(r.json()["languages"], [])
|
|
finally:
|
|
install_zz()
|
|
|
|
# ── who may install or alter one ─────────────────────────────────────────
|
|
def test_a_guest_cannot_install_or_alter_a_translation(self):
|
|
g = self.guest()
|
|
r = g.post("/api/plugins/install", json={"source": str(PLUGIN_DIR), "approve": True})
|
|
self.assertIn(r.status_code, (400, 403), r.text)
|
|
self.assertFalse(DEPS.plugin_store.list_for("dom"))
|
|
with self.assertRaises(ManifestError):
|
|
DEPS.plugin_store.install("dom", str(PLUGIN_DIR), is_owner=False, approve=True)
|
|
for method, path, body in (("put", "/api/plugins/translation-zz", {"enabled": False}),
|
|
("delete", "/api/plugins/translation-zz", None),
|
|
("post", "/api/plugins/translation-zz/reload", {})):
|
|
r = getattr(g, method)(path, **({"json": body} if body is not None else {}))
|
|
self.assertIn(r.status_code, (400, 403, 404), (path, r.text))
|
|
self.assertEqual(langs(), ("en", "zz")) # still installed, still enabled
|
|
|
|
def test_the_owners_plugin_page_shows_the_coverage(self):
|
|
r = TestClient(main.app).get("/api/plugins/translation-zz/settings", headers=OWNER_H)
|
|
self.assertEqual(r.status_code, 200, r.text)
|
|
typed = r.json()["typed"]
|
|
self.assertEqual((typed["kind"], typed["lang"], typed["active"]), ("translation", "zz", True))
|
|
self.assertEqual(typed["coverage"]["missing"], 0)
|
|
self.assertEqual(r.json()["languages"], ["en", "zz"])
|
|
|
|
# ── errors a guest can hit ───────────────────────────────────────────────
|
|
def test_guest_errors_follow_their_language_and_keep_their_kind(self):
|
|
r = self.guest().post("/api/spawn", json={"prompt": "x", "projects": []})
|
|
self.assertEqual(r.status_code, 400)
|
|
self.assertEqual(r.json()["detail"], {"message": zz("pick one of your projects"),
|
|
"kind": "guest_project"})
|
|
# their stored pick wins over the browser's
|
|
DEPS.users.update("dom", {"lang": "en"})
|
|
r = self.guest().post("/api/spawn", json={"prompt": "x", "projects": []})
|
|
self.assertEqual(r.json()["detail"]["message"], "pick one of your projects")
|
|
caller = guest_from_record({**DEPS.users.get("dom"), "lang": "zz"})
|
|
with self.assertRaises(Exception) as e:
|
|
guest_runs.check_model(caller, "opus")
|
|
self.assertEqual(e.exception.detail["kind"], "guest_model")
|
|
self.assertTrue(e.exception.detail["message"].startswith("⟦"))
|
|
|
|
def test_a_guest_route_refusal(self):
|
|
r = self.guest().get("/api/users")
|
|
self.assertEqual(r.status_code, 403)
|
|
self.assertEqual(r.json()["detail"], zz("not available to guests"))
|
|
|
|
# ── the system prompt ────────────────────────────────────────────────────
|
|
def test_a_guests_run_gets_the_translations_line(self):
|
|
zed = guest_from_record({**DEPS.users.get("dom"), "lang": "zz"})
|
|
en = guest_from_record({**DEPS.users.get("dom"), "lang": "en"})
|
|
for scope in (guest_runs.scope_for(zed, "film", "chat"),
|
|
guest_runs.staging_scope(zed, [], "- line")):
|
|
self.assertIn("Dom reads Zedish", scope["systemPrompt"])
|
|
for scope in (guest_runs.scope_for(en, "film", "chat"),
|
|
guest_runs.staging_scope(en, [], "- line")):
|
|
self.assertNotIn("Zedish", scope["systemPrompt"])
|
|
|
|
def test_spawned_run_gets_the_line_from_the_browser_language(self):
|
|
calls = []
|
|
orig = run_routes._send_message
|
|
run_routes._send_message = lambda deps, prompt, **kw: (
|
|
calls.append(kw) or {"sessionId": "new", "pid": 1})
|
|
self.addCleanup(setattr, run_routes, "_send_message", orig)
|
|
r = self.guest().post("/api/spawn", json={"prompt": "salut", "projects": ["film"]})
|
|
self.assertEqual(r.status_code, 200, r.text)
|
|
self.assertIn("reads Zedish", calls[0]["scope"]["systemPrompt"])
|
|
|
|
# ── the app's own pushes ─────────────────────────────────────────────────
|
|
def test_shared_notice_reaches_each_guest_in_their_language(self):
|
|
DEPS.users.update("dom", {"lang": "zz", "notify": {"channels": ["in_app", "webpush"]}})
|
|
pushed = []
|
|
orig = deliver.push
|
|
deliver.push = lambda deps, uid, title, message, url, extra=None: (
|
|
pushed.append((uid, title, message)) or [])
|
|
self.addCleanup(setattr, deliver, "push", orig)
|
|
|
|
def note(lang):
|
|
return {"title": tr(lang, "Tap to answer"), "message": tr(lang, "Tap to answer")}
|
|
deliver.to_guests(DEPS, ["owner", "dom"], "Tap to answer", "Tap to answer",
|
|
"https://x/conversations", "https://x", None, localized(note))
|
|
self.assertEqual(pushed, [("dom", zz("Tap to answer"), zz("Tap to answer"))])
|
|
|
|
def test_feeds_show_a_stored_notice_in_the_readers_language(self):
|
|
from notifications.routes import _with_url
|
|
n = {"title": "⏳ X waits for Gabriel's OK", "body": "b", "url": "",
|
|
"i18n": {"zz": {"title": "⏳ X ⟦waits⟧", "body": "bb"}}}
|
|
zed = guest_from_record({**DEPS.users.get("dom"), "lang": "zz"})
|
|
self.assertEqual(_with_url(zed, n), {"title": "⏳ X ⟦waits⟧", "body": "bb", "url": ""})
|
|
self.assertEqual(_with_url(OWNER, n), {"title": "⏳ X waits for Gabriel's OK",
|
|
"body": "b", "url": ""})
|
|
|
|
# ── the sign-in mail ─────────────────────────────────────────────────────
|
|
def test_sign_in_mail_in_the_guests_language(self):
|
|
sent = []
|
|
orig = mailer.send
|
|
mailer.send = lambda to, subject, text, html=None: sent.append((subject, text, html))
|
|
self.addCleanup(setattr, mailer, "send", orig)
|
|
mailer.login_mail("dom@example.com", "Dom <3", "https://x/login?token=t", 15, "zz")
|
|
subject, text, html = sent[0]
|
|
self.assertEqual(subject, zz(f"Sign in to {mailer.APP_NAME}"))
|
|
self.assertTrue(text.startswith(zz("Hi Dom <3,")))
|
|
self.assertIn("Dom <3", html)
|
|
mailer.login_mail("dom@example.com", "Dom", "https://x", 15)
|
|
self.assertEqual(sent[1][0], f"Sign in to {mailer.APP_NAME}")
|
|
|
|
def test_sign_in_mail_follows_the_request_for_auto(self):
|
|
langs_ = []
|
|
orig_enabled, orig_mail = mailer.enabled, mailer.login_mail
|
|
mailer.enabled = lambda: True
|
|
mailer.login_mail = lambda to, name, url, minutes, lang="en", code="": langs_.append(lang)
|
|
self.addCleanup(setattr, mailer, "enabled", orig_enabled)
|
|
self.addCleanup(setattr, mailer, "login_mail", orig_mail)
|
|
import users.routes as user_routes
|
|
self.addCleanup(setattr, user_routes, "_background", user_routes._background)
|
|
user_routes._background = lambda fn, *a: fn(*a) # the mail leaves inline here
|
|
c = TestClient(main.app, base_url="https://claude.example.test",
|
|
headers={"Accept-Language": "zz-ZZ,zz;q=0.8"})
|
|
self.assertEqual(c.post("/api/auth/request-link",
|
|
json={"email": "dom@example.com"}).status_code, 200)
|
|
self.assertEqual(langs_, ["zz"])
|
|
|
|
|
|
class Seed(unittest.TestCase):
|
|
def test_a_translation_is_seeded_once(self):
|
|
from plugins import carryover
|
|
from plugins.store import PluginStore
|
|
seed = pathlib.Path(tempfile.mkdtemp())
|
|
make_translation(seed)
|
|
store = PluginStore(pathlib.Path(tempfile.mkdtemp()) / "plugins")
|
|
self.assertEqual(carryover.seed_typed_plugins(store, seed), ["translation-zz"])
|
|
store.uninstall(OWNER_UID, "translation-zz")
|
|
self.assertEqual(carryover.seed_typed_plugins(store, seed), []) # an uninstall sticks
|
|
|
|
|
|
def tearDownModule():
|
|
uninstall_zz()
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main()
|