A plugin's translations now live in that plugin: "i18n": "i18n" in plugin.json
→ i18n/en.json (the English source list, generated by the plugins repo's
scripts/plugin_i18n.py) + i18n/<lang>.json (English → translation).
- plugins/plugin_i18n.py: validation (the folder, en.json an array, each
<lang>.json an object; every file's language added to `languages`),
per-language coverage (missing / stale / placeholder mismatches), the bundle.
- GET /api/plugins/i18n/{lang}: every active plugin's dictionary in one ETag'd
body (a guest: their installs + the managed plugins granted to them).
- Frames: init.i18n + init.locale, aiAgentPlugin.t / tn (English fallback).
- Manifest labels (nav, drawers, header, Files/Projects/Dashboards, settings
subtitle + fields) through pluginT: plugin dictionary → core t() → English.
- Handlers get AIA_LANGS (the hub's languages); they read their own file.
- /api/plugins/{id}/info|settings carry `i18n` coverage; the plugin page shows
"Its strings in <language>" rows.
- plugins/hubi18n.py: the owner-only i18n.read bridge (operator approval) —
translations' and plugins' coverage, files only — for the auto-translate plugin.
- docs/plugins.md ("A plugin's own strings"), CLAUDE.md, i18n README; openapi +
generated types, authz golden, ui key list regenerated.
Changelog
- Added: plugins can ship their own translations (i18n/<lang>.json), shown per language on their page.
- Added: the i18n.read bridge the auto-translate plugin uses to keep translations complete.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
192 lines
9.3 KiB
Python
192 lines
9.3 KiB
Python
"""A plugin's own strings (``plugin.json`` ``i18n`` → ``i18n/en.json`` +
|
|
``i18n/<lang>.json``, ``plugins/plugin_i18n.py``): the manifest field, the
|
|
coverage on the plugin's page, ``GET /api/plugins/i18n/{lang}`` (the PWA's
|
|
bundle — a guest's managed plugins included), the owner-only ``i18n.read``
|
|
bridge (the auto-translate plugin) and ``AIA_LANGS`` for handlers."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
import os
|
|
import pathlib
|
|
import tempfile
|
|
import unittest
|
|
from types import SimpleNamespace
|
|
from unittest.mock import patch
|
|
|
|
TMP = pathlib.Path(tempfile.mkdtemp())
|
|
for k, v in {"DB_PATH": TMP / "x.db", "TRANSCRIPTS_DIR": TMP / "t", "WORKSPACE": TMP, "REPO_DIR": TMP,
|
|
"META_PATH": TMP / "meta.json", "USERS_PATH": TMP / "users.json", "AUTH_PATH": TMP / "auth.json",
|
|
"PROJECTS_DIR": TMP / "projects", "SERVICES_DIR": TMP / "services",
|
|
"INTERNAL_API_TOKEN": "tok", "SIDECAR_TOKEN": "", "PI_TRANSCRIPTS_DIR": ""}.items():
|
|
os.environ.setdefault(k, str(v))
|
|
|
|
from fastapi.testclient import TestClient # noqa: E402
|
|
|
|
import main # noqa: E402
|
|
from plugins import hubi18n, plugin_i18n # noqa: E402
|
|
from plugins import routes as plugin_routes # noqa: E402
|
|
from plugins.manifest import ManifestError, requires_operator, validate_manifest # noqa: E402
|
|
from plugins.store import OWNER_UID, PluginStore # noqa: E402
|
|
from toolproxy import access # noqa: E402
|
|
|
|
APP = {"schema": 1, "id": "greeter", "name": "Greeter", "i18n": "i18n",
|
|
"ui": {"pages": [{"id": "hi", "label": "Hello page", "nav": "dashboards", "html": "ui/hi.html"}]}}
|
|
EN = ["Hello page", "Hello {name}", "Gone soon"]
|
|
FR = {"Hello page": "Page bonjour", "Hello {name}": "Bonjour {nom}", "Old one": "Ancienne"}
|
|
|
|
|
|
def _plugin(root: pathlib.Path, manifest: dict, en=EN, langs: dict | None = None) -> pathlib.Path:
|
|
(root / "ui").mkdir(parents=True, exist_ok=True)
|
|
(root / "handlers").mkdir(exist_ok=True)
|
|
(root / "plugin.json").write_text(json.dumps(manifest))
|
|
(root / "ui" / "hi.html").write_text("<p>hi</p>")
|
|
(root / "handlers" / "env.py").write_text(
|
|
"import json, os, sys\nsys.stdin.read()\nprint(json.dumps({'langs': json.loads(os.environ['AIA_LANGS'])}))\n")
|
|
if manifest.get("i18n"):
|
|
d = root / manifest["i18n"]
|
|
d.mkdir(exist_ok=True)
|
|
if en is not None:
|
|
(d / "en.json").write_text(json.dumps(en))
|
|
for code, dct in (langs if langs is not None else {"fr": FR}).items():
|
|
(d / f"{code}.json").write_text(json.dumps(dct, ensure_ascii=False))
|
|
return root
|
|
|
|
|
|
class ManifestTest(unittest.TestCase):
|
|
def test_files_complete_languages(self):
|
|
with tempfile.TemporaryDirectory() as d:
|
|
mf = validate_manifest(_plugin(pathlib.Path(d) / "p", APP, langs={"fr": FR, "de": {}}))
|
|
self.assertEqual(mf["i18n"], "i18n")
|
|
self.assertEqual(mf["languages"], ["en", "de", "fr"])
|
|
|
|
def test_no_field_no_change(self):
|
|
with tempfile.TemporaryDirectory() as d:
|
|
mf = validate_manifest(_plugin(pathlib.Path(d) / "p", {k: v for k, v in APP.items() if k != "i18n"}))
|
|
self.assertNotIn("i18n", mf)
|
|
self.assertEqual(mf["languages"], ["en"])
|
|
|
|
def test_needs_the_source_list(self):
|
|
with tempfile.TemporaryDirectory() as d:
|
|
with self.assertRaises(ManifestError) as e:
|
|
validate_manifest(_plugin(pathlib.Path(d) / "p", APP, en=None))
|
|
self.assertIn("en.json", str(e.exception))
|
|
|
|
def test_rejects_bad_paths_and_shapes(self):
|
|
with tempfile.TemporaryDirectory() as d:
|
|
root = _plugin(pathlib.Path(d) / "p", APP)
|
|
for bad in ("../x", "/abs", "nope", 3):
|
|
(root / "plugin.json").write_text(json.dumps({**APP, "i18n": bad}))
|
|
with self.assertRaises(ManifestError):
|
|
validate_manifest(root)
|
|
with self.assertRaises(ManifestError):
|
|
validate_manifest(_plugin(pathlib.Path(d) / "q", APP, langs={"fr": ["not", "a", "dict"]}))
|
|
|
|
def test_i18n_read_is_operator_only(self):
|
|
with tempfile.TemporaryDirectory() as d:
|
|
mf = validate_manifest(_plugin(pathlib.Path(d) / "p", {**APP, "capabilities": ["i18n.read"]}))
|
|
self.assertTrue(requires_operator(mf))
|
|
|
|
|
|
class CoverageTest(unittest.TestCase):
|
|
def test_counts(self):
|
|
with tempfile.TemporaryDirectory() as d:
|
|
root = _plugin(pathlib.Path(d) / "p", APP)
|
|
cov = plugin_i18n.coverage({"manifest": APP, "dir": str(root)})
|
|
fr = cov["langs"]["fr"]
|
|
self.assertEqual(cov["source"], 3)
|
|
self.assertEqual((fr["total"], fr["translated"], fr["missing"], fr["stale"]), (3, 2, 1, 1))
|
|
self.assertEqual(fr["missingSample"], ["Gone soon"])
|
|
self.assertEqual(fr["staleSample"], ["Old one"])
|
|
self.assertEqual(fr["placeholderMismatch"], ["Hello {name}"])
|
|
self.assertIsNone(plugin_i18n.coverage({"manifest": {}, "dir": str(root)}))
|
|
|
|
def test_dictionary_falls_back_to_nothing(self):
|
|
with tempfile.TemporaryDirectory() as d:
|
|
root = _plugin(pathlib.Path(d) / "p", APP)
|
|
di = plugin_i18n.i18n_dir(root, APP)
|
|
self.assertEqual(plugin_i18n.dictionary(di, "en"), {})
|
|
self.assertEqual(plugin_i18n.dictionary(di, "de"), {})
|
|
self.assertEqual(plugin_i18n.dictionary(di, "../x"), {})
|
|
self.assertEqual(plugin_i18n.dictionary(di, "fr")["Hello page"], "Page bonjour")
|
|
|
|
|
|
class RoutesTest(unittest.TestCase):
|
|
def setUp(self):
|
|
self.tmp = tempfile.TemporaryDirectory()
|
|
self.root = pathlib.Path(self.tmp.name)
|
|
self.store = PluginStore(self.root / "data")
|
|
self.store.install(OWNER_UID, str(_plugin(self.root / "greeter", APP)), is_owner=True, approve=True)
|
|
tr = {"schema": 1, "id": "auto-translate", "name": "Auto-translate",
|
|
"capabilities": ["i18n.read"],
|
|
"actions": {"env": {"script": "handlers/env.py"}}}
|
|
self.store.install(OWNER_UID, str(_plugin(self.root / "auto-translate", tr)), is_owner=True, approve=True)
|
|
self.deps = main.app.state.ai
|
|
self.tc = TestClient(main.app, base_url="http://127.0.0.1:8096", client=("127.0.0.1", 5000))
|
|
self.p = patch.object(self.deps, "plugin_store", self.store)
|
|
self.p.start()
|
|
|
|
def tearDown(self):
|
|
self.p.stop()
|
|
self.tmp.cleanup()
|
|
|
|
def test_bundle_for_the_owner(self):
|
|
r = self.tc.get("/api/plugins/i18n/fr")
|
|
self.assertEqual(r.status_code, 200, r.text)
|
|
self.assertEqual(r.json()["plugins"], {"greeter": FR})
|
|
again = self.tc.get("/api/plugins/i18n/fr", headers={"If-None-Match": r.headers["etag"]})
|
|
self.assertEqual(again.status_code, 304)
|
|
self.assertEqual(self.tc.get("/api/plugins/i18n/de").json()["plugins"], {})
|
|
self.assertEqual(self.tc.get("/api/plugins/i18n/x1").status_code, 400)
|
|
|
|
def test_bundle_for_a_guest_holds_only_their_plugins(self):
|
|
guest = SimpleNamespace(is_owner=False, id="dom")
|
|
req = SimpleNamespace(headers={})
|
|
out = json.loads(plugin_routes.plugins_i18n(self.deps, guest, "fr", req).body)
|
|
self.assertEqual(out["plugins"], {}) # the owner's plain install isn't theirs
|
|
with patch.object(self.store, "managed_plugins",
|
|
return_value=[self.store.get_raw(OWNER_UID, "greeter")]), \
|
|
patch.object(self.store, "effective_grant", return_value={"enabled": True}):
|
|
out = json.loads(plugin_routes.plugins_i18n(self.deps, guest, "fr", req).body)
|
|
self.assertEqual(list(out["plugins"]), ["greeter"])
|
|
|
|
def test_info_and_settings_carry_coverage(self):
|
|
info = self.tc.get("/api/plugins/greeter/info").json()
|
|
self.assertEqual(info["i18n"]["langs"]["fr"]["missing"], 1)
|
|
self.assertEqual(info["languages"], ["en", "fr"])
|
|
st = self.tc.get("/api/plugins/greeter/settings").json()
|
|
self.assertEqual(st["i18n"]["source"], 3)
|
|
|
|
def _bridge(self, uid=OWNER_UID, pid="auto-translate"):
|
|
return self.tc.get(f"/proxy/tools/plugins/{pid}/hub/i18n",
|
|
headers={"Authorization": f"Bearer {access.mint_handler(uid, pid, ttl=600)}"})
|
|
|
|
def test_bridge_lists_plugins_and_coverage(self):
|
|
r = self._bridge()
|
|
self.assertEqual(r.status_code, 200, r.text)
|
|
body = r.json()
|
|
g = next(p for p in body["plugins"] if p["id"] == "greeter")
|
|
self.assertEqual(g["i18n"]["langs"]["fr"]["missing"], 1)
|
|
a = next(p for p in body["plugins"] if p["id"] == "auto-translate")
|
|
self.assertIsNone(a["i18n"])
|
|
self.assertEqual(body["translations"], [])
|
|
|
|
def test_bridge_refuses_a_guest_and_a_plugin_without_the_capability(self):
|
|
self.assertEqual(self._bridge("dom").status_code, 403)
|
|
self.assertEqual(self._bridge(pid="greeter").status_code, 403)
|
|
|
|
def test_repo_path(self):
|
|
self.assertEqual(hubi18n.repo_path("/workspace/projects/ai-agent-plugins/plugins/cron-jobs"),
|
|
"plugins/cron-jobs")
|
|
self.assertIsNone(hubi18n.repo_path("/tmp/x"))
|
|
|
|
def test_handlers_get_the_hub_languages(self):
|
|
r = self.tc.post("/api/plugins/auto-translate/actions/env", json={})
|
|
self.assertEqual(r.status_code, 200, r.text)
|
|
body = r.json()
|
|
self.assertEqual((body.get("result") or body)["langs"][0], "en")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main()
|