Files
ai-agent/backend/test_notify_channels.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

214 lines
9.6 KiB
Python

"""Notification channels a plugin contributes (``provides: notify.channel``,
2026-11-25): who runs, what each gets, failures, clears, the
carry-over of the core's Home Assistant webhook."""
from __future__ import annotations
import json
import pathlib
import tempfile
import time
import unittest
from types import SimpleNamespace
from unittest.mock import patch
from notifications import channels
from notifications.store import NotifyStore
from plugins import carryover
from plugins.manifest import ManifestError, capability_summary, validate_manifest
from plugins.store import OWNER_UID, PluginStore
# Records what it got (one JSON line per call) and answers per the push's
# title: "fail" → refused, "boom" → crash, else delivered.
SEND = r'''
import json, os, pathlib, sys
d = json.load(sys.stdin)
p = pathlib.Path(os.environ["AIA_PLUGIN_DATA_DIR"]) / "got.jsonl"
with p.open("a") as f:
f.write(json.dumps({**d, "uid": json.loads(os.environ["AIA_USER_CONTEXT"])["uid"]}) + "\n")
t = (d.get("push") or {}).get("title")
if t == "boom":
raise SystemExit(3)
if t == "fail":
print(json.dumps({"ok": False, "status": 502, "error": "upstream down"}))
elif t == "final":
print(json.dumps({"ok": False, "status": 400, "error": "bad", "retry": False}))
else:
print(json.dumps({"ok": True, "status": 200}))
'''
MANIFEST = {
"schema": 1, "id": "chan", "name": "Channel",
"actions": {"send": {"script": "handlers/send.py", "timeoutSec": 10}},
"provides": {"notify.channel": "send"},
}
def _write(root: pathlib.Path, manifest: dict) -> pathlib.Path:
(root / "handlers").mkdir(parents=True, exist_ok=True)
(root / "plugin.json").write_text(json.dumps(manifest))
(root / "handlers" / "send.py").write_text(SEND)
return root
class ChannelsTest(unittest.TestCase):
def setUp(self):
self.tmp = tempfile.TemporaryDirectory()
self.root = pathlib.Path(self.tmp.name)
self.store = PluginStore(self.root / "data")
self.pdir = _write(self.root / "plugin", MANIFEST)
self.deps = SimpleNamespace(plugin_store=self.store,
users=SimpleNamespace(get=lambda u: None))
def tearDown(self):
self.tmp.cleanup()
def got(self, uid=OWNER_UID):
p = self.store.user_data_dir(uid, "chan") / "got.jsonl"
return [json.loads(x) for x in p.read_text().splitlines()] if p.exists() else []
def install(self, uid=OWNER_UID):
self.store.install(uid, str(self.pdir), is_owner=True, approve=True)
def test_manifest(self):
mf = validate_manifest(self.pdir)
self.assertEqual(mf["provides"], {"notify.channel": "send"})
self.assertTrue(any("pushes" in c["label"] for c in capability_summary(mf)))
with self.assertRaises(ManifestError):
validate_manifest(_write(self.root / "q", {**MANIFEST, "provides": {"notify.channel": "x"}}))
def test_no_channel_no_delivery(self):
self.assertEqual(channels.deliver(self.deps, OWNER_UID, "notify", {"title": "t"}), [])
def test_delivers_the_push_as_is(self):
self.install()
push = {"event": "notify", "id": "ntf_0123456789ab", "title": "t", "message": "m",
"url": "https://x", "image": "https://x/i.png", "type": "deploy",
"importance": "high", "actions": [{"action": "ntf_0123456789ab__0", "title": "Go"}]}
out = channels.deliver(self.deps, OWNER_UID, "notify", push)
self.assertEqual(out, [{"channel": "chan", "ok": True, "status": 200}])
[g] = self.got()
self.assertEqual(g["event"], "notify")
self.assertEqual(g["push"], push)
self.assertEqual(g["uid"], OWNER_UID)
def test_only_the_users_own_enabled_installs(self):
self.install("dom")
self.assertEqual(channels.deliver(self.deps, OWNER_UID, "notify", {"title": "t"}), [])
self.assertEqual(len(channels.deliver(self.deps, "dom", "notify", {"title": "t"})), 1)
self.assertEqual(self.got("dom")[0]["uid"], "dom")
self.store.update("dom", "chan", enabled=False)
self.assertEqual(channels.deliver(self.deps, "dom", "notify", {"title": "t"}), [])
def test_a_failure_is_recorded_not_retried(self):
self.install()
out = channels.deliver(self.deps, OWNER_UID, "notify", {"title": "fail"})
self.assertEqual(out, [{"channel": "chan", "ok": False, "status": 502,
"error": "upstream down"}])
time.sleep(0.2)
self.assertEqual(len(self.got()), 1)
def test_a_crash_is_a_failure_not_an_exception(self):
self.install()
[r] = channels.deliver(self.deps, OWNER_UID, "ask", {"title": "boom"})
self.assertFalse(r["ok"])
self.assertTrue(r["error"])
def test_clear_goes_off_thread(self):
self.install()
channels.clear_async(self.deps, OWNER_UID, ["ask_1", "", "frm_2"])
for _ in range(100):
if self.got():
break
time.sleep(0.05)
[g] = self.got()
self.assertEqual(g["event"], "clear")
self.assertEqual(g["push"], {"event": "clear", "tags": ["ask_1", "frm_2"]})
class DeliverTest(unittest.TestCase):
"""``notifications.service._deliver``: the owner's channels + web push."""
def setUp(self):
self.tmp = tempfile.TemporaryDirectory()
root = pathlib.Path(self.tmp.name)
self.store = PluginStore(root / "data")
self.pdir = _write(root / "plugin", MANIFEST)
self.store.install(OWNER_UID, str(self.pdir), is_owner=True, approve=True)
self.notify = NotifyStore(str(root / "notifications.json"))
self.deps = SimpleNamespace(plugin_store=self.store, notify_store=self.notify,
users=SimpleNamespace(get=lambda u: None, active=lambda u: None),
push=SimpleNamespace(count=lambda u: 0))
def tearDown(self):
self.tmp.cleanup()
def test_owner_in_the_app_then_the_channel(self):
from notifications import service
out = service._deliver(self.deps, ["owner"], "notify",
{"event": "notify", "id": "ntf_aaaaaaaaaaaa", "title": "t"},
"t", "m", "https://x")
self.assertEqual(out, [{"target": "in_app", "ok": True, "user": "owner"},
{"channel": "chan", "ok": True, "status": 200, "user": "owner"}])
self.assertTrue(service._ok(["owner"], out))
def test_no_channel_is_still_ok(self):
from notifications import service
self.store.uninstall(OWNER_UID, "chan")
out = service._deliver(self.deps, ["owner"], "notify", {"event": "notify", "title": "t"},
"t", "m", "https://x")
self.assertEqual(out, [{"target": "in_app", "ok": True, "user": "owner"}])
self.assertTrue(service._ok(["owner"], out))
def test_a_guest_gets_their_own_channel_in_their_words(self):
from notifications import service
from users import deliver
self.store.install("dom", str(self.pdir), is_owner=True, approve=True)
self.deps.users = SimpleNamespace(
get=lambda u: None,
active=lambda u: {"id": u, "lang": "fr", "notify": {"channels": ["in_app"]}})
from i18n_testkit import speaking
with patch.object(deliver, "GUEST_PUBLIC_URL", "https://guest.example"), speaking("fr"):
out = service._deliver(
self.deps, ["dom"], "notify",
{"event": "notify", "id": "ntf_bbbbbbbbbbbb", "title": "Done", "message": "m",
"url": service.VIEW_URL + "/conversation/x", "account": "work"},
"Done", "m", service.VIEW_URL + "/conversation/x",
i18n={"fr": {"title": "Fini", "message": "ok"}})
self.assertEqual([r.get("channel") or r.get("target") for r in out], ["in_app", "chan"])
got = [json.loads(x) for x in (self.store.user_data_dir("dom", "chan") / "got.jsonl")
.read_text().splitlines()]
push = got[0]["push"]
self.assertEqual((push["title"], push["message"]), ("Fini", "ok"))
self.assertEqual(push["url"], "https://guest.example/conversation/x")
self.assertNotIn("account", push)
self.assertFalse((self.store.user_data_dir(OWNER_UID, "chan") / "got.jsonl").exists())
class CarryOverTest(unittest.TestCase):
def test_ha_webhook_moves_to_the_plugin_once(self):
with tempfile.TemporaryDirectory() as t:
root = pathlib.Path(t)
legacy = root / "notifications.json"
legacy.write_text(json.dumps({"webhooks": [
{"id": "home-assistant", "name": "Home Assistant",
"url": "http://host.docker.internal:8123/api/webhook/ai_agent",
"events": ["notify", "ask"], "enabled": True,
"pwaPackage": "org.chromium.webapk.a8bca040319cce682_v2"}],
"notifications": []}))
notify = NotifyStore(str(legacy))
store = PluginStore(root / "data")
self.assertTrue(carryover.ha_webhook(store, notify))
got = json.loads((store.user_data_dir(OWNER_UID, "home-assistant-push")
/ "legacy-webhook.json").read_text())
self.assertEqual(got["url"], "http://host.docker.internal:8123/api/webhook/ai_agent")
self.assertEqual(got["pwaPackage"], "org.chromium.webapk.a8bca040319cce682_v2")
self.assertEqual(notify.legacy_webhooks(), [])
self.assertFalse(carryover.ha_webhook(store, notify)) # a no-op once done
# A restart doesn't bring the list back.
self.assertEqual(NotifyStore(str(legacy)).legacy_webhooks(), [])
if __name__ == "__main__":
unittest.main()