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>
182 lines
8.1 KiB
Python
182 lines
8.1 KiB
Python
"""
|
|
Who a push, ask or form reaches — the conversation's **audience**
|
|
(``users/access.audience``): whoever started it, the people it's shared with,
|
|
the owner once they follow a guest's conversation, minus whoever muted it.
|
|
Each person is reached on their own channels:
|
|
|
|
* the **owner** — their channel plugins (``notifications/channels.py``: the
|
|
``home-assistant-push`` plugin → the phone) and a web push on each browser
|
|
they turned push on from (Settings);
|
|
* a **guest** — the channels they chose (``users.json`` → ``notify.channels``):
|
|
|
|
* ``in_app`` — always: the feed and the waiting-for-feedback list are
|
|
filtered per user, and the SSE ping reaches their open tabs.
|
|
* ``webpush`` — a notification on each device they turned push on from
|
|
(``users/webpush.py``; the service worker draws it, an ask with its
|
|
buttons), sent off the request thread.
|
|
* their own channel plugins, if they installed one (an ntfy, a Telegram…).
|
|
|
|
There is no per-push mail (dropped 2026-11-01 for a weekly recap).
|
|
|
|
A notice the **app** words itself (not the agent) may carry ``i18n``
|
|
variants (``core.i18n.localized``): each guest gets the one in their
|
|
language (``core.i18n.effective_lang``), the owner the English.
|
|
|
|
A push with no session (a host script, the owner's guest-start ping) is the
|
|
owner's. Besides their own conversations, the owner hears about a guest only
|
|
when one *starts* a conversation on the lab (:func:`owner_ping_start`) — not
|
|
one on their own computer.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import logging
|
|
import os
|
|
import time
|
|
|
|
from core.i18n import effective_lang, pick
|
|
from users import access, push_style, webpush
|
|
from users.caller import OWNER_ID
|
|
|
|
log = logging.getLogger("ai-agent.deliver")
|
|
|
|
# The guest surface's public origin — what links in a guest's mail point at.
|
|
GUEST_PUBLIC_URL = os.environ.get("GUEST_PUBLIC_URL", "").rstrip("/")
|
|
|
|
|
|
def recipients(deps, session_id: str) -> list[str]:
|
|
"""The user ids a push from ``session_id`` goes to (``owner`` included)."""
|
|
sid = (session_id or "").strip()
|
|
if not sid:
|
|
return [OWNER_ID]
|
|
return access.audience(deps.meta_store.peek(sid))
|
|
|
|
|
|
def guest_url(owner_url: str, view_url: str) -> str:
|
|
"""Rebase a link from the owner's viewer onto the guest surface."""
|
|
if GUEST_PUBLIC_URL and owner_url.startswith(view_url):
|
|
return GUEST_PUBLIC_URL + owner_url[len(view_url):]
|
|
return owner_url
|
|
|
|
|
|
def url_for(caller, url: str, view_url: str) -> str:
|
|
"""A recorded link as ``caller`` can open it: on the guest surface for a
|
|
guest, on the admin host for the owner (older guest pushes stored the
|
|
guest host's link)."""
|
|
if not url:
|
|
return url
|
|
if not caller.is_owner:
|
|
return guest_url(url, view_url)
|
|
if GUEST_PUBLIC_URL and url.startswith(GUEST_PUBLIC_URL):
|
|
return view_url + url[len(GUEST_PUBLIC_URL):]
|
|
return url
|
|
|
|
|
|
def to_guests(deps, to: list[str], title: str, message: str, url: str,
|
|
view_url: str, extra: dict | None = None,
|
|
i18n: dict | None = None, push: dict | None = None) -> list[dict]:
|
|
"""Fan a push out to every guest in ``to`` — each delivery record tagged
|
|
with its ``user``. ``extra`` rides along to the web push (``kind``,
|
|
``id``, an ask's ``options`` — see :func:`to_guest`); ``i18n`` holds the
|
|
notice in other languages (``{"fr": {"title", "message"}}``); ``push``
|
|
is the channel payload (``notifications/channels.py``) for the guests'
|
|
own channel plugins, with their wording and link."""
|
|
from notifications import channels
|
|
out: list[dict] = []
|
|
for uid in to:
|
|
if uid == OWNER_ID:
|
|
continue
|
|
user = deps.users.active(uid)
|
|
if user:
|
|
v = pick(i18n, effective_lang(user)) or {}
|
|
g_url = guest_url(url, view_url)
|
|
rows = to_guest(deps, user, v.get("title") or title,
|
|
v.get("message") or message, g_url, extra)
|
|
if push:
|
|
own = {**push, "url": g_url}
|
|
if push.get("event") == "notify":
|
|
own.update({"title": v.get("title") or push.get("title") or "",
|
|
"message": v.get("message") or push.get("message") or ""})
|
|
own.pop("account", None) # the owner's seats are none of theirs
|
|
rows += channels.deliver(deps, uid, push.get("event") or "notify", own)
|
|
out += [{**r, "user": uid} for r in rows]
|
|
return out
|
|
|
|
|
|
def to_guest(deps, user: dict, title: str, message: str, url: str,
|
|
extra: dict | None = None) -> list[dict]:
|
|
"""Fan a push out to the guest's channels; returns delivery records shaped
|
|
like the webhook ones (``{target, ok, …}``). ``extra`` is merged into the
|
|
web push payload: ``kind`` (notify | ask | form), ``id`` (the log entry
|
|
— an ask's buttons answer it), ``type``, ``options``."""
|
|
channels = (user.get("notify") or {}).get("channels") or ["in_app"]
|
|
out = [{"target": "in_app", "ok": True}]
|
|
if "webpush" in channels:
|
|
out += push(deps, user["id"], title, message, url, extra)
|
|
return out
|
|
|
|
|
|
def push(deps, uid: str, title: str, message: str, url: str,
|
|
extra: dict | None = None) -> list[dict]:
|
|
"""A web push to every device of ``uid`` (the owner's too), queued off
|
|
the request thread; one delivery record, or none without a device."""
|
|
if not deps.push.count(uid):
|
|
return []
|
|
payload = {"kind": "notify", **(extra or {}), "title": title,
|
|
"body": message, "url": url,
|
|
"timestamp": int(time.time() * 1000)}
|
|
style = push_style.style_of(payload["kind"], payload.get("type") or "")
|
|
level = deps.push.level(uid, push_style.group_of(style))
|
|
if level == "off":
|
|
return []
|
|
payload.update(push_style.look(style))
|
|
if payload.get("image") and payload.get("id"):
|
|
# From the app, whoever sent it (notifications/image_proxy.py).
|
|
payload["image"] = f"/api/notify/{payload['id']}/image"
|
|
if level == "silent":
|
|
payload["silent"] = True
|
|
webpush.send_async(deps.push, uid, payload)
|
|
return [{"target": "webpush", "ok": True, "queued": True,
|
|
**({"silent": True} if level == "silent" else {})}]
|
|
|
|
|
|
def clear(deps, session_id: str, tag: str, kind: str = "ask", *,
|
|
only: str | None = None, phone: bool = True) -> None:
|
|
"""Take a push off the devices it reached once it is dealt with — an ask
|
|
answered or expired, a form submitted / cancelled / closed, a push read
|
|
or swiped away in the app — wherever that happened (``tag`` = the push's
|
|
tag: an ask's or a form's id, else the push's own).
|
|
|
|
Its conversation's audience (``only``: just that user — what one person
|
|
read is theirs) on their web push devices and their channel plugins, the
|
|
owner's (the phone) (``phone=False``: it was the phone that dismissed it). A
|
|
user who has the group off never got it, so gets no clear either (a push
|
|
that draws nothing costs the site Chrome's patience)."""
|
|
if not tag:
|
|
return
|
|
group = push_style.group_of(kind)
|
|
from notifications import channels
|
|
to = [only] if only else recipients(deps, session_id)
|
|
for uid in to:
|
|
if deps.push.count(uid) and deps.push.level(uid, group) != "off":
|
|
webpush.send_async(deps.push, uid, {"kind": "clear", "tag": tag})
|
|
if uid != OWNER_ID:
|
|
channels.clear_async(deps, uid, [tag])
|
|
if phone and OWNER_ID in to:
|
|
from notifications.service import clear_phone
|
|
clear_phone(deps, [tag])
|
|
|
|
|
|
def owner_ping_start(deps, caller, slug: str, prompt: str) -> None:
|
|
"""The one push the owner gets about a guest: they started something on
|
|
the lab (a run on their own computer pings nobody)."""
|
|
from notifications.service import VIEW_URL, _create_notify
|
|
first = " ".join((prompt or "").split())[:160]
|
|
try:
|
|
_create_notify(deps, {
|
|
"title": f"👤 {caller.name} started a conversation",
|
|
"message": f"{slug} · {first}",
|
|
"type": "ai", "url": f"{VIEW_URL}/conversations", "sessionId": ""})
|
|
except Exception as exc: # never fail the spawn over the ping
|
|
log.warning("owner ping failed: %s", exc)
|