Files
gabrielvidalandClaude Opus 5.5 c80c9e2323 feat(notifications): notification channels a plugin contributes; Home Assistant delivery leaves the core
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>
2026-11-25 17:50:55 +01:00

486 lines
22 KiB
Python

"""Creating and recording pushes and asks, and the flat notification feed."""
import datetime
import logging
import os
import pathlib
import re
import threading
import time
import uuid as uuidlib
from fastapi import HTTPException
import accounts as accounts_mod
from conversations import ids
from conversations.cards import _conv_meta, _conv_title
from conversations.catalog import _conv_ids_by_session
from conversations.tree import _conv_id
from core.config import SOURCE_DIRS
from core.state import AppState
from notifications import channels, store as notify_mod
from users import access, deliver
from users.caller import OWNER, OWNER_ID, Caller
log = logging.getLogger("ai-agent.notifications")
# ── flat notification feed (server-side mirror of the frontend's buildFeed) ──
# The PWA flattens /api/notifications + /api/notify-log into one list of feed
# items (lib/notifications.ts). The phone can't run that, so we do the same
# flattening here — same stable ids — for the unread endpoint and the read
# ledger. Keep the two in sync: id scheme is `<convId>#<at>#<index>` for
# conv-linked pushes and `log#<id>` for hub-only entries.
_DEDUP_WINDOW_MS = 120_000
def _parse_iso_ms(at: str | None) -> float | None:
if not at:
return None
try:
s = at.replace("Z", "+00:00")
return datetime.datetime.fromisoformat(s).timestamp() * 1000.0
except (ValueError, AttributeError):
return None
def _same_push(e: dict, n: dict) -> bool:
"""Is hub-log entry ``e`` the copy of a conversation's push ``n`` (same
title and body, within the dedup window)? The feeds show the latter."""
if (n.get("title") or "") != (e.get("title") or "") \
or (n.get("body") or "") != (e.get("body") or ""):
return False
t, nt = _parse_iso_ms(e.get("at")), _parse_iso_ms(n.get("at"))
return t is None or nt is None or abs(nt - t) <= _DEDUP_WINDOW_MS
def conversation_feed_ids(deps: AppState, sids) -> list[str]:
"""Every feed id the owner's read ledger knows these conversations'
pushes by (``sids``: session ids) — ``<conv>#<at>#<i>`` for each push
recorded on each of their transcripts (a duplicate the feeds fold away
included: ``?new=1`` checks every one), and ``log#<id>`` for what a
session pushed without recording it on its conversation (an ask). An ask
still waiting for its answer is left out: archiving isn't answering it.
Only the conversations the owner hears — the others aren't in his feed."""
want: dict[str, list[dict]] = {}
for sid in dict.fromkeys(s for s in sids if s):
meta = deps.meta_store.peek(sid)
if access.hears(OWNER, meta):
want[sid] = meta.get("notifications") or []
if not want:
return []
out: list[str] = []
for path, s in deps.store.all_summaries():
sid = s.get("sessionId") or ""
if sid not in want or not s.get("messages") or s.get("isSidechain"):
continue
cid = _conv_id(path)
out += [f"{cid}#{n.get('at') or ''}#{i}" for i, n in enumerate(want[sid])]
for e in deps.notify_store.log(limit=500):
sid = e.get("sessionId") or ""
if sid not in want or not e.get("id"):
continue
if e.get("kind") == "ask" and e.get("status") == "pending":
continue
if any(_same_push(e, n) for n in want[sid]):
continue # the conversation's own copy is the feed's
out.append(f"log#{e['id']}")
return list(dict.fromkeys(out))
def _flat_notifications(deps: AppState) -> list[dict]:
"""Every notification **the owner hears** as a flat, de-duplicated,
newest-first feed item — the exact set the owner's PWA shows, so "unread"
means the same on the phone. A guest's conversation the owner doesn't
follow isn't in it (``users/access.audience``)."""
feed: list[dict] = []
for path, s in deps.store.all_summaries():
if not s.get("messages") or s.get("isSidechain"):
continue
sid = s.get("sessionId") or ""
meta = deps.meta_store.peek(sid)
notes = meta.get("notifications") or []
if not notes or not access.hears(OWNER, meta):
continue
m = _conv_meta(deps, s)
cid = _conv_id(path)
title = _conv_title(deps, s)
last_seen: dict[str, float] = {}
for i, n in enumerate(notes):
key = (f"{n.get('title') or ''} {n.get('body') or ''} "
f"{n.get('type') or ''} {n.get('url') or ''}")
t = _parse_iso_ms(n.get("at"))
prev = last_seen.get(key)
if prev is not None and (t is None or abs(t - prev) <= _DEDUP_WINDOW_MS):
continue # duplicate push within the conversation
if t is not None:
last_seen[key] = t
feed.append({
"id": f"{cid}#{n.get('at') or ''}#{i}",
"convId": cid, "convTitle": title,
"title": n.get("title") or "", "body": n.get("body") or "",
"type": n.get("type") or "", "url": n.get("url") or "",
"image": n.get("image") or "",
"at": n.get("at"),
"projects": m.get("projects") or [],
"services": m.get("services") or [],
"kind": "notify",
"spoken": n.get("spoken") or "",
})
# Merge the hub log: a log entry that matches a conv push (title+body within
# the dedup window) is a duplicate and skipped; hub-only entries are added.
for e in deps.notify_store.log(limit=500):
if not log_heard(deps, OWNER, e):
continue
t = _parse_iso_ms(e.get("at"))
dup = False
for n in feed:
if n["title"] == (e.get("title") or "") and \
n["body"] == (e.get("body") or ""):
nt = _parse_iso_ms(n.get("at"))
if t is None or nt is None or abs(nt - t) <= _DEDUP_WINDOW_MS:
dup = True
break
if dup:
continue
feed.append({
"id": f"log#{e.get('id')}",
"convId": "", "convTitle": "",
"title": e.get("title") or "", "body": e.get("body") or "",
"type": e.get("type") or "", "url": e.get("url") or "",
"image": e.get("image") or "",
"at": e.get("at"),
"projects": [], "services": [],
"kind": e.get("kind") or "notify",
})
feed.sort(key=lambda n: n.get("at") or "", reverse=True)
return feed
# How many conversations the home page's New list fetched before the feed was
# paged (``useNotifications(60)``) — all a PWA could ever have shown as new.
OLD_HOME_WINDOW = 60
def old_home_edge(deps: AppState, before: str) -> str | None:
"""The oldest push the owner's home could show at ``before`` (ISO): the
oldest one, from before then, of the :data:`OLD_HOME_WINDOW` conversations
that ended last — what the unpaged home fetched. The read ledger's
``baseline`` at the one-time import: older pushes were only ever "new" in
lists no screen rendered, so paging back to them mustn't bring them in."""
window: list[tuple[str, str]] = []
for _path, s in deps.store.all_summaries():
if not s.get("messages") or s.get("isSidechain"):
continue
meta = deps.meta_store.peek(s.get("sessionId") or "")
ats = [n["at"] for n in meta.get("notifications") or []
if n.get("at") and n["at"] < before]
if ats and access.hears(OWNER, meta):
window.append((s.get("endedAt") or "", min(ats)))
window.sort(reverse=True)
return min((at for _, at in window[:OLD_HOME_WINDOW]), default=None)
def log_heard(deps: AppState, caller: Caller, entry: dict) -> bool:
"""Is a hub-log entry (push / ask) one ``caller`` hears? A session's
entries follow its conversation's audience as it stands now; one with no
session (a host script, a guest-start ping) is the owner's."""
sid = entry.get("sessionId") or ""
if not sid:
return caller.is_owner
return access.hears(caller, deps.meta_store.peek(sid))
# Where the viewer lives, for the links a push carries when the caller gave
# no --url: the conversation that sent it.
VIEW_URL = os.environ.get("AI_AGENT_VIEW_URL",
"https://ai-agent.lab.gabvdl.xyz").rstrip("/")
_CLIENT_ID_RE = re.compile(r"^(ntf|ask|frm)_[0-9a-f]{12}$")
def _client_id(given: str | None, prefix: str) -> str:
"""A caller-minted id (the notify CLI's), validated, else a fresh one."""
given = (given or "").strip()
if given:
if not _CLIENT_ID_RE.match(given) or not given.startswith(prefix + "_"):
raise HTTPException(400, f"bad id {given!r} (want {prefix}_<12 hex>)")
return given
return f"{prefix}_{uuidlib.uuid4().hex[:12]}"
def session_account(deps: AppState, session_id: str) -> str:
"""The Claude account a session runs under, when its sidecar stamped it
(a spawned run's ``account`` / an import's ``accountSource``) — else "".
Never guessed onto the default: an unstamped push stays unscoped."""
if not session_id:
return ""
m = deps.meta_store.peek(session_id)
return (accounts_mod.valid(m.get("account"))
or accounts_mod.valid(m.get("accountSource")) or "")
def _conversation_url(deps: AppState, session_id: str) -> str:
"""The viewer page of the session that is notifying — the default link
of every push, ask and form. Resolved **here** rather than in the CLI
because only the hub knows where a worker's transcript was mirrored to:
the indexed summary first, else the transcript on disk under any source
dir (a session too young to be indexed), else the conversations list."""
sid = (session_id or "").strip()
if not sid:
return f"{VIEW_URL}/conversations"
cid = _conv_ids_by_session(deps, ).get(sid)
if not cid:
for root in SOURCE_DIRS:
for hit in pathlib.Path(root).glob(f"*/{sid}.jsonl"):
# Not archived yet: mint its uid off the live copy (the
# archive keeps the same relative path, so the same uid).
cid = ids.REGISTRY.uid(f"{hit.parent.name}/{hit.name}", hit)
break
if cid:
break
return f"{VIEW_URL}/conversation/{cid}" if cid else f"{VIEW_URL}/conversations"
def _stamp_notified(deps: AppState, session_id: str, note: dict, final: bool) -> None:
"""What ``conv-meta notify`` used to do from the skill: record the push on
the conversation's metadata (the viewer's notification feed + the
``notified`` lifecycle check) and, for the closing push, mark it
finished — which reads "running" until the sign-off it precedes lands or
the run exits (``_resolve_state``). Best-effort; never fails the push."""
sid = (session_id or "").strip()
if not sid:
return
patch: dict = {"notification": note}
if final:
patch["state"] = "finished"
try:
deps.meta_store.update(sid, patch)
deps.hub.publish({"type": "meta", "id": sid})
except Exception:
pass
def _ok(to: list[str], delivered: list[dict]) -> bool:
"""Every delivery went through — and something was delivered, unless
nobody was meant to hear it (everyone muted the conversation)."""
return all(x["ok"] for x in delivered) and (bool(delivered) or not to)
def _deliver(deps: AppState, to: list[str], event: str, payload: dict,
title: str, message: str, url: str, kind: str = "",
i18n: dict | None = None) -> list[dict]:
"""Reach everyone in ``to`` on their channels: the owner through their
channel plugins (``notifications/channels.py`` — Home Assistant → the
phone) and their web push devices, each guest through theirs
(users/deliver.py). ``kind`` (notify | ask | form, default ``event``)
tells a web push what it is; ``i18n`` is the app's own wording in other
languages, for the guests who read them."""
out: list[dict] = []
extra = {"kind": kind or event, "id": payload.get("id") or "",
**{k: payload[k] for k in ("type", "options", "image", "tag")
if payload.get(k)}}
if OWNER_ID in to:
# In the app always (the feed, SSE); then the channel plugins and the
# web push devices. No channel set up is not a failure.
out += [{**r, "user": OWNER_ID} for r in
[{"target": "in_app", "ok": True}]
+ channels.deliver(deps, OWNER_ID, event, payload)
+ deliver.push(deps, OWNER_ID, title, message, url, extra)]
return out + deliver.to_guests(deps, to, title, message, url, VIEW_URL, extra, i18n,
push=payload)
def clear_phone(deps: AppState, tags: list[str]) -> None:
"""Ask the owner's channels (Home Assistant → the phone) to take ``tags``
off the screen — ``{"event": "clear", "tags": […]}``, off the request
thread. A channel that never got one of them ignores it."""
channels.clear_async(deps, OWNER_ID, tags)
def push_tag(entry: dict) -> str:
"""What a recorded push is tagged with on the devices: its own ``tag``
(a form's id) or its id."""
return entry.get("tag") or entry.get("id") or ""
def entries_for_feed_ids(deps: AppState, ids: list[str],
sessions: set[str] | None = None) -> list[dict]:
"""The hub log entries behind feed ids — ``log#<id>``, or a
conversation's ``<conv>#<at>#<i>`` (its push was stamped with the log
entry's own ``at``). ``sessions``: only those sessions' entries (another
conversation may have pushed the same second)."""
want_ids, want_at = set(), set()
for fid in ids:
if fid.startswith("log#"):
want_ids.add(fid[4:])
elif fid.count("#") >= 2:
want_at.add(fid.rsplit("#", 2)[1])
if not want_ids and not want_at:
return []
return [e for e in deps.notify_store.log(limit=notify_mod._MAX_LOG)
if (e.get("id") in want_ids or (e.get("at") and e["at"] in want_at))
and (sessions is None or e.get("sessionId") in sessions)]
def feed_ids_for(deps: AppState, entries: list[dict]) -> list[str]:
"""The feed ids the read ledger knows these log entries by."""
ats = {e.get("at") for e in entries if e.get("at")}
out = [f"log#{e['id']}" for e in entries if e.get("id")]
if ats:
# A conversation's copy of the push carries the entry's `at`; another
# hub-only entry sent the same second is a different push.
out += [n["id"] for n in _flat_notifications(deps)
if n.get("at") in ats and not n["id"].startswith("log#")]
return list(dict.fromkeys(out))
def sweep_expired_asks(deps: AppState) -> int:
"""Flip pending asks past their expiry to ``expired`` and take them off
the devices — an ask otherwise only expires when someone reads it."""
n = 0
for e in deps.notify_store.log(limit=notify_mod._MAX_LOG):
if e.get("kind") != "ask" or e.get("status") != "pending":
continue
cur = deps.notify_store.ask_status(e["id"])
if cur and cur.get("status") == "expired":
from users import deliver as deliver_mod
deliver_mod.clear(deps, cur.get("sessionId") or "", cur["id"])
deps.hub.publish({"type": "notification", "id": cur["id"]})
n += 1
return n
def start_ask_sweeper(deps: AppState, every_s: float = 300) -> None:
def loop():
while True:
time.sleep(every_s)
try:
sweep_expired_asks(deps)
except Exception:
log.exception("ask sweep failed")
threading.Thread(target=loop, daemon=True, name="ask-sweeper").start()
def _create_notify(deps: AppState, d: dict) -> dict:
"""Record a push and deliver it to the conversation's audience. ``d`` is
a NotifyBody dump — the route and the outbox mirror both come through
here. The owner hears it on the webhooks, each guest on their own
channels (users/deliver.py); a push with no session is the owner's.
A notice the app words itself may add ``i18n`` (``core.i18n.localized``:
``{"fr": {"title", "message"}}``): each guest is pushed the one in their
language, and the feeds show it to them (``notifications/routes.py``).
Never forwarded to the webhooks — the owner reads English."""
i18n = d.pop("i18n", None) or None
nid = _client_id(d.get("id"), "ntf")
sid = (d.get("sessionId") or "").strip()
# A form's push (forms/, askform/) says so — a guest's web push draws it
# as one; never forwarded.
kind = "form" if d.pop("pushKind", None) == "form" else "notify"
if sid:
# The run's cost is the backend's exact list price (the CLI's own line is
# restated), and the closing push adds how much of the plan's week it
# used (usage/calibrate.py) — best effort, never blocks the push.
try:
from usage.calibrate import restate_cost
d["message"] = restate_cost(deps, sid, d.get("message") or "",
bool(d.get("final")))
except Exception:
pass
if not (d.get("url") or "").strip():
d["url"] = _conversation_url(deps, sid)
# The conversation's main resources (INS-2229, #13722…) as they are now,
# for the notification card's pills — never blocks the push.
try:
from conversations.resource_view import notif_resources
resources = notif_resources(deps, sid)
except Exception:
resources = []
# A plugin's push to one named user with no conversation behind it
# (plugins/proxyroutes.py hub/notify).
forced_to = d.pop("recipients", None)
to = list(forced_to) if forced_to else deliver.recipients(deps, sid)
if d.get("final") and sid:
# A child's closing push stays in the hub: its answer goes back to the
# conversation that started it (runs/children.py), whose own closing
# push is the one the phone hears. Recorded all the same — the card
# after the message, the finished stamp. (`--no-report` pushes.)
from runs import children
if children.reports_back(deps.meta_store.peek(sid)):
to = []
actions = [a for a in (d.get("actions") or [])
if isinstance(a, dict) and a.get("action") and a.get("title")]
payload = {"event": "notify", "id": nid,
**{k: v for k, v in d.items()
if k not in ("sessionId", "id", "final") and v not in (None, "", [])}}
# Which Claude account the push belongs to, so the phone side can keep
# work pushes on their own channels (the HA integration's WORK_CHANNELS).
account = session_account(deps, sid)
if account:
payload["account"] = account
delivered = _deliver(deps, to, "notify", payload, d.get("title") or "",
d.get("message") or "", d["url"], kind, i18n)
# Stored as the feeds show it: ``{lang: {"title", "body"}}``.
variants = {lang: {"title": v.get("title") or "", "body": v.get("message") or ""}
for lang, v in (i18n or {}).items() if isinstance(v, dict)}
entry = {
"id": nid, "kind": "notify", "title": d.get("title") or "",
"body": d.get("message") or "", "type": d.get("type") or "",
"url": d.get("url") or "", "image": d.get("image") or "",
# A form's push is tagged with the form's id (on the phone and the
# web push devices) — what a clear names it by.
**({"tag": d["tag"]} if d.get("tag") else {}),
"at": notify_mod._now_iso(), "sessionId": sid,
"to": to, "delivered": delivered,
# Kept (not just forwarded) so the UI can replay what the phone said.
"spoken": d.get("spoken") or "",
}
if resources:
entry["resources"] = resources
if variants:
entry["i18n"] = variants
if actions:
entry.update({"actions": actions, "status": "sent",
"actionIndex": None, "actionTitle": None, "actedAt": None})
deps.notify_store.watch_actions(nid)
deps.notify_store.record(entry)
_stamp_notified(deps, sid, {"title": entry["title"], "body": entry["body"],
"type": entry["type"], "url": entry["url"],
"at": entry["at"],
**({"resources": resources} if resources else {}),
**({"i18n": variants} if variants else {})},
bool(d.get("final")))
deps.hub.publish({"type": "notification", "id": nid})
return {"ok": _ok(to, delivered), "id": nid, "delivered": delivered,
"url": entry["url"]}
def _create_ask(deps: AppState, d: dict) -> dict:
"""Create an ask, forward it, return its id (AskBody dump in)."""
options = [o.strip() for o in (d.get("options") or []) if o and o.strip()]
if not (d.get("question") or "").strip() or not 2 <= len(options) <= 3:
raise HTTPException(400, "need a question and 2-3 options")
nid = _client_id(d.get("id"), "ask")
sid = (d.get("sessionId") or "").strip()
url = (d.get("url") or "").strip() or _conversation_url(deps, sid)
to = deliver.recipients(deps, sid)
ask = deps.notify_store.create_ask(
d["question"].strip(), options, type_=d.get("type") or "",
url=url, image=d.get("image") or "", session_id=sid,
timeout_s=d.get("timeoutSecs") or notify_mod.DEFAULT_ASK_TIMEOUT_S,
nid=nid)
payload = {"event": "ask", "id": ask["id"], "question": ask["body"],
"options": options, "url": url,
**{k: v for k, v in d.items()
if k in ("type", "image", "icon", "color")
and v not in (None, "")}}
account = session_account(deps, sid)
if account:
payload["account"] = account
delivered = _deliver(deps, to, "ask", payload, "❓ " + ask["body"],
" / ".join(options), url)
deps.notify_store.set_delivered(ask["id"], delivered, to)
deps.hub.publish({"type": "notification", "id": ask["id"]})
return {"ok": _ok(to, delivered), "id": ask["id"], "delivered": delivered,
"url": url}