Files
ai-agent/backend/test_i18n.py
gabrielvidalandClaude Opus 5.5 24b9723fd3 refactor(new-project): New project moves to a live plugin
backend/newproject/ (policy, form, service, store, routes, edge shim),
its schemas and test, and `notify new-project` are gone — the
`new-project` plugin (ai-agent-plugins) owns the form, the policy, the
quota, the approval and the scaffold. The core keeps the spawn, read off
the plugin's composer mode (plugins/waiting.composer_modes_for):

- /api/spawn newProject: refused unless the mode allows it; the guest
  staging dir/scope/note live in users/runs.py (the staging scope now
  carries the guest's tool proxy so the plugin's skill reaches the hub)
- /api/me.newProjects from the mode (None without the plugin)
- /api/users/{uid}/domain(+/setup) move to users/routes.py (users/edge.py)
- hub scaffold/relocate keeps the guest's tools + scope line
- plugins/carryover.new_project: /data/new-projects.json, the
  guestDefaults.newProjects policy and projects.create guests carried
  over once (requests.json, plugin config, managed grants)
- frontend: composer toggle / + New project entry driven by
  usePluginComposerModes(); Every guest drops the policy + requests
  (link to Settings → Plugins → New project); the Web address card stays,
  without the Can create projects switch

authz/matrix.golden.txt not updated (the coordinator regenerates it).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 20:12:01 +01:00

324 lines
17 KiB
Python
Raw Permalink Blame History

This file contains invisible Unicode characters
This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""French for guests on the backend (core/i18n.py): the ``tr`` helper and
its dictionary, a user's ``lang`` / ``browserLang`` and the API around them,
and the guest-facing text that follows it — errors, the sign-in mail, the
app's own pushes, the New project form, the run's system prompt.
Imports ``main`` against throwaway paths (no startup event → no threads)."""
import ast
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",
"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 (effective_lang, localized, pick, primary_lang, # noqa: E402
tr)
from core.i18n_fr import FR # 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"}
NBSP = " "
BACKEND = pathlib.Path(__file__).resolve().parent
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 or f.name == "i18n_fr.py":
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 _vars(s: str) -> list[str]:
return sorted(re.findall(r"\{(\w+)\}", s))
class Tr(unittest.TestCase):
def test_english_is_the_key(self):
self.assertEqual(tr("en", "login required"), "login required")
self.assertEqual(tr("fr", "login required"), "connexion requise")
def test_missing_entry_or_language_falls_back_to_english(self):
self.assertEqual(tr("fr", "nobody translated {thing}", thing="this"),
"nobody translated this")
for lang in (None, "", "de", "auto"):
self.assertEqual(tr(lang, "login required"), "login required")
def test_placeholders(self):
self.assertEqual(tr("fr", "Hi {name},", name="Dom"), "Bonjour 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}")
self.assertEqual(tr("fr", "monthly budget reached (${spent} of ${budget})",
spent="12.50", budget="40"),
f"budget du mois atteint (12.50{NBSP}$ sur 40{NBSP}$)")
def test_every_literal_has_french_and_every_entry_is_used(self):
used = _literals()
missing = {k: w for k, w in used.items() if k not in FR}
self.assertEqual(missing, {}, "tr()/msg() literals with no French entry")
self.assertEqual(sorted(set(FR) - set(used)), [], "French entries nothing uses")
def test_french_keeps_the_placeholders_and_the_style(self):
for en, fr in FR.items():
self.assertEqual(_vars(en), _vars(fr), en)
self.assertTrue(fr.strip(), en)
# a no-break space before : ; ! ? (not inside a URL) and inside « »
self.assertIsNone(re.search(r"[^ /] ?[;!?](\s|$)|[^ :/]:(\s|$)", fr), fr)
self.assertNotIn("« ", fr)
self.assertNotIn(" »", fr)
def test_localized_and_pick(self):
v = localized(lambda lang: {"title": tr(lang, "Tap to answer")})
self.assertEqual(v, {"fr": {"title": "Touche pour répondre"}})
self.assertEqual(pick(v, "fr"), {"title": "Touche pour répondre"})
self.assertIsNone(pick(v, "en"))
self.assertIsNone(pick(None, "fr"))
class Lang(unittest.TestCase):
def test_primary_language_of_a_header(self):
self.assertEqual(primary_lang("fr-FR,fr;q=0.9,en-US;q=0.8,en;q=0.7"), "fr")
self.assertEqual(primary_lang("en-GB"), "en")
self.assertEqual(primary_lang("en;q=0.5, fr;q=0.9"), "fr")
self.assertIsNone(primary_lang("de-DE,en;q=0.5")) # another first choice
self.assertIsNone(primary_lang(""))
self.assertIsNone(primary_lang(None))
self.assertIsNone(primary_lang("*"))
def test_effective_language(self):
self.assertEqual(effective_lang({"lang": "fr", "browserLang": "en"}), "fr")
self.assertEqual(effective_lang({"lang": "auto", "browserLang": "fr"}, "en"), "fr")
self.assertEqual(effective_lang({"lang": "auto"}, "fr-FR,fr"), "fr")
self.assertEqual(effective_lang({}, "de"), "en")
self.assertEqual(effective_lang(None), "en")
class Users(unittest.TestCase):
def setUp(self):
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="fr-FR,fr;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": "FR"})["lang"], "fr")
with self.assertRaises(ValueError):
DEPS.users.update("dom", {"lang": "de"})
self.assertEqual(DEPS.users.get("dom")["lang"], "fr")
def test_browser_language_written_only_when_it_changes(self):
self.assertTrue(DEPS.users.set_browser_lang("dom", "fr"))
self.assertFalse(DEPS.users.set_browser_lang("dom", "fr"))
self.assertFalse(DEPS.users.set_browser_lang("dom", "de")) # left as it was
self.assertFalse(DEPS.users.set_browser_lang("dom", None))
self.assertEqual(DEPS.users.get("dom")["browserLang"], "fr")
self.assertEqual(DEPS.users.lang_of("dom"), "fr")
DEPS.users.update("dom", {"lang": "en"})
self.assertEqual(DEPS.users.lang_of("dom"), "en")
self.assertEqual(DEPS.users.lang_of("owner"), "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"], "fr")
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")
owner = TestClient(main.app).get("/api/me", headers=OWNER_H).json()
self.assertEqual(owner["lang"], "en")
def test_owner_sets_a_guests_language(self):
c = TestClient(main.app)
r = c.put("/api/users/dom", json={"lang": "fr"}, headers=OWNER_H)
self.assertEqual((r.status_code, r.json()["lang"]), (200, "fr"), 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"]), ("fr", "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": "fr-FR"})
r = c.post("/api/auth/login", json={"token": "nope"})
self.assertEqual(r.status_code, 401)
self.assertEqual(r.json()["detail"], {"message": "ce lien est invalide ou expiré",
"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"], "fr")
# ── 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": "choisis un de tes projets",
"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": "fr"})
with self.assertRaises(Exception) as e:
guest_runs.check_model(caller, "opus")
self.assertEqual(e.exception.detail["kind"], "guest_model")
self.assertIn("n'est pas activé pour toi", e.exception.detail["message"])
def test_a_guest_route_refusal(self):
r = self.guest().get("/api/users")
self.assertEqual(r.status_code, 403)
self.assertEqual(r.json()["detail"], "pas disponible pour les invités")
# ── the system prompt ────────────────────────────────────────────────────
def test_a_french_guests_run_is_told_to_write_french(self):
fr = guest_from_record({**DEPS.users.get("dom"), "lang": "fr"})
en = guest_from_record({**DEPS.users.get("dom"), "lang": "en"})
for scope in (guest_runs.scope_for(fr, "film", "chat"),
guest_runs.staging_scope(fr, [], "- line")):
self.assertIn("reads French", scope["systemPrompt"])
self.assertIn("--lang fr", scope["systemPrompt"])
self.assertIn('"tu"', scope["systemPrompt"])
for scope in (guest_runs.scope_for(en, "film", "chat"),
guest_runs.staging_scope(en, [], "- line")):
self.assertNotIn("French", 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 French", 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": "fr", "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", "Touche pour répondre", "Touche pour répondre")])
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": {"fr": {"title": "⏳ X attend le feu vert de Gabriel", "body": "bb"}}}
fr = guest_from_record({**DEPS.users.get("dom"), "lang": "fr"})
self.assertEqual(_with_url(fr, n), {"title": "⏳ X attend le feu vert de Gabriel",
"body": "bb", "url": ""})
self.assertEqual(_with_url(OWNER, n), {"title": "⏳ X waits for Gabriel's OK",
"body": "b", "url": ""})
def test_test_push_in_the_guests_language(self):
from users import routes as user_routes, webpush
sent = []
orig = webpush.send
webpush.send = lambda store, uid, payload: sent.append(payload) or []
self.addCleanup(setattr, webpush, "send", orig)
orig_count = DEPS.push.count
DEPS.push.count = lambda uid: 1
self.addCleanup(setattr, DEPS.push, "count", orig_count)
DEPS.users.update("dom", {"lang": "fr"})
user_routes._test_push(DEPS, "dom", None, "fr")
self.assertEqual(sent[0]["title"], "🔔 Les notifications push marchent")
self.assertIn("Envoyée par toi.", sent[0]["body"])
# ── the sign-in mail ─────────────────────────────────────────────────────
def test_sign_in_mail_in_french(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, "fr")
subject, text, html = sent[0]
self.assertEqual(subject, f"Se connecter à {mailer.APP_NAME}")
self.assertTrue(text.startswith("Bonjour Dom <3,"))
self.assertIn("expire dans 15 minutes", text)
self.assertIn("Bonjour Dom &lt;3,", html)
mailer.login_mail("dom@example.com", "Dom", "https://x", 15)
self.assertEqual(sent[1][0], f"Sign in to {mailer.APP_NAME}")
mailer.invite_mail("dom@example.com", "Dom", "https://x", inviter="Gabriel",
projects=["film"], expires="3 jours", home="https://h/login",
lang="fr")
self.assertEqual(sent[2][0], f"Gabriel t'invite sur {mailer.APP_NAME}")
self.assertIn("<b>film</b>", sent[2][2])
self.assertIn('<a href="https://h/login">', sent[2][2])
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": "fr-CA,fr;q=0.8"})
self.assertEqual(c.post("/api/auth/request-link",
json={"email": "dom@example.com"}).status_code, 200)
self.assertEqual(langs, ["fr"])
if __name__ == "__main__":
unittest.main()