A plugin declaring provides: {"notify.channel": "<action>"} gets every
push, ask and clear of the person who installed it (notifications/channels.py),
the payload the HA webhook always got. Tried once, no retry; with no channel
a push is still in the app (an in_app record, ok) and on the browsers, which
stay core. Guests' own channel installs get their wording and guest link.
Removed: the webhook list (Settings → Webhooks, /api/webhooks*, forward(),
the seeded HA webhook) and integrations/home-assistant, now in the
home-assistant-push plugin (ai-agent-plugins). The old webhook's URL and PWA
package are carried over once into the plugin's data. /settings/webhooks
redirects to the plugin. Forms ha-push-as-a-plugin_yjj2n0,
browser-push-as-a-plugin_7id9we.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
213 lines
9.6 KiB
Python
213 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"]}})
|
|
with patch.object(deliver, "GUEST_PUBLIC_URL", "https://guest.example"):
|
|
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()
|