Files
ai-agent/backend/test_notify_audio.py
gabrielvidalandClaude Opus 5.5 fccc844486 refactor(notifications): the replay sound comes from a notify.audio plugin
backend/notifications/audio.py is gone (119 lines: the phone-bridge client,
its in-process memo and a duplicate of the bridge's speech sanitizer). The
desk-phone live plugin (ai-agent-plugins, `provides: notify.audio`) renders
and caches the WAV now.

- notifications/channels.render_audio: runs the owner's active notify.audio
  action with {spoken, type, title, message, audio}, decodes `wavBase64`
  (checked for RIFF); AudioUnavailable when there is no provider or it fails.
- POST /api/notifications/audio keeps its route and authz
  (notifications.ledger) and answers 503 instead of 502 when nothing can
  render; its body takes the optional `audio` clip too (openapi + orval
  regenerated).
- NotificationCard hides NotifSoundButton unless
  usePluginProvides("notify.audio"); the mock lists notify.audio.
- `spoken`, GET /api/notifications/unread and the phone scope stay core.
- test_notify_audio.py: no provider, payload, plugin error / not a WAV /
  crash, disabled and guest installs, the route's 503 → WAV.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 10:33:07 +01:00

130 lines
5.4 KiB
Python

"""A push's sound from a plugin (``provides: notify.audio``, the desk-phone
plugin, 2026-11-26): ``notifications.channels.render_audio`` and
``POST /api/notifications/audio`` — the owner's provider only, its payload,
its WAV decoded, 503 without one or when it fails."""
from __future__ import annotations
import base64
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", "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 notifications import channels # noqa: E402
from plugins.store import OWNER_UID, PluginStore # noqa: E402
OWNER_H = {"X-Internal-Auth": os.environ["INTERNAL_API_TOKEN"]}
WAV = b"RIFF\x24\x00\x00\x00WAVEfmt fake"
# Records its stdin; answers per the spoken line.
RENDER = r'''
import base64, json, os, pathlib, sys
p = json.load(sys.stdin)
(pathlib.Path(os.environ["AIA_PLUGIN_DATA_DIR"]) / "got.json").write_text(json.dumps(p))
s = p.get("spoken")
if s == "down":
print(json.dumps({"_error": {"status": 502, "kind": "bridge_error", "message": "bridge unreachable"}}))
elif s == "html":
print(json.dumps({"ok": True, "wavBase64": base64.b64encode(b"<html>").decode()}))
elif s == "boom":
raise SystemExit(3)
else:
print(json.dumps({"ok": True, "contentType": "audio/wav",
"wavBase64": base64.b64encode(%r).decode()}))
''' % WAV
MANIFEST = {"schema": 1, "id": "desk-phone", "name": "Desk Phone",
"actions": {"render": {"script": "handlers/render.py", "timeoutSec": 30}},
"provides": {"notify.audio": "render"}}
def _write(root: pathlib.Path) -> pathlib.Path:
(root / "handlers").mkdir(parents=True, exist_ok=True)
(root / "plugin.json").write_text(json.dumps(MANIFEST))
(root / "handlers" / "render.py").write_text(RENDER)
return root
class RenderAudio(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")
self.deps = SimpleNamespace(plugin_store=self.store, users=SimpleNamespace(get=lambda u: None))
def tearDown(self):
self.tmp.cleanup()
def install(self, uid=OWNER_UID):
self.store.install(uid, str(self.pdir), is_owner=True, approve=True)
def got(self) -> dict:
return json.loads((self.store.user_data_dir(OWNER_UID, "desk-phone") / "got.json").read_text())
def test_no_provider(self):
self.assertIsNone(channels.audio_provider(self.deps))
with self.assertRaises(channels.AudioUnavailable):
channels.render_audio(self.deps, {"spoken": "Salut"})
def test_renders_and_passes_the_push(self):
self.install()
wav = channels.render_audio(self.deps, {"spoken": "C'est fait.", "type": "deploy",
"title": "T", "message": None, "extra": "x"})
self.assertEqual(wav, WAV)
self.assertEqual(self.got(), {"spoken": "C'est fait.", "type": "deploy", "title": "T",
"message": "", "audio": ""})
def test_plugin_error_not_a_wav_or_crash(self):
self.install()
for spoken, needle in (("down", "bridge unreachable"), ("html", "no WAV"), ("boom", "")):
with self.assertRaises(channels.AudioUnavailable) as cm:
channels.render_audio(self.deps, {"spoken": spoken})
self.assertIn(needle, str(cm.exception), spoken)
def test_disabled_or_a_guests_install_is_no_provider(self):
self.install("dom")
self.assertIsNone(channels.audio_provider(self.deps))
self.install()
self.assertIsNotNone(channels.audio_provider(self.deps))
self.store.update(OWNER_UID, "desk-phone", enabled=False)
self.assertIsNone(channels.audio_provider(self.deps))
class AudioRoute(unittest.TestCase):
def test_503_without_then_wav_with_a_provider(self):
deps = main.app.state.ai
client = TestClient(main.app, headers=OWNER_H)
with tempfile.TemporaryDirectory() as td:
store = PluginStore(pathlib.Path(td) / "data")
with patch.object(deps, "plugin_store", store):
none = client.post("/api/notifications/audio", json={"spoken": "Salut", "type": "code"})
store.install(OWNER_UID, str(_write(pathlib.Path(td) / "src")), is_owner=True, approve=True)
ok = client.post("/api/notifications/audio", json={"spoken": "Salut", "type": "code"})
bad = client.post("/api/notifications/audio", json={"spoken": "down"})
self.assertEqual(none.status_code, 503)
self.assertIn("notify.audio", none.json()["detail"])
self.assertEqual(ok.status_code, 200)
self.assertEqual(ok.headers["content-type"], "audio/wav")
self.assertEqual(ok.content, WAV)
self.assertEqual(bad.status_code, 503)
self.assertIn("bridge unreachable", bad.json()["detail"])
if __name__ == "__main__":
unittest.main()