diff --git a/docs/NOTIFICATIONS.md b/docs/NOTIFICATIONS.md index 837cbec..1eafca1 100644 --- a/docs/NOTIFICATIONS.md +++ b/docs/NOTIFICATIONS.md @@ -43,6 +43,10 @@ copy, including the phone's content key. Each alert shows the agent's name, picture and the start of its message (up to 1,600 characters). Event IDs are stable (`:`), so a retry never produces a second alert. +A reply, task or helper alert goes out from the Hermes process that ran the turn as soon as the reply is saved. +One Hermes process also owns a background sender that retries anything that didn't go out; both claim each alert +before sending, so it's sent once. Approval alerts wait a short grace period and stay with that sender. + ### Silent replies Agents can answer with a silence marker such as `[SILENT]` or `NO_REPLY` when there's nothing to say. A reply diff --git a/loopdy_plugin/link_contracts.py b/loopdy_plugin/link_contracts.py index 5a38591..d0230b7 100644 --- a/loopdy_plugin/link_contracts.py +++ b/loopdy_plugin/link_contracts.py @@ -112,7 +112,7 @@ def parse_direct_enrollment(payload: dict[str, Any]) -> dict[str, Any]: "body_fat_percentage", "workout", ) -PLUGIN_VERSION = "2.18.1" +PLUGIN_VERSION = "2.18.2" AVAILABLE_WIKI_OPERATIONS = available_wiki_operations() GROUPS_OPERATIONS = frozenset( { diff --git a/loopdy_plugin/managed_notifications.py b/loopdy_plugin/managed_notifications.py index 1ec1fc4..89b45e2 100644 --- a/loopdy_plugin/managed_notifications.py +++ b/loopdy_plugin/managed_notifications.py @@ -137,6 +137,10 @@ def host_request_transcript(method: str, path: str, grant_id: str, timestamp: in return "\n".join(("loopdy-notification-host-v1", method, path, grant_id, str(timestamp), nonce, hashlib.sha256(raw).hexdigest())).encode() +def _send_in_background(work: Callable[[], None]) -> None: + threading.Thread(target=work, name="loopdy-managed-notifications-now", daemon=True).start() + + class _NoRedirect(HTTPRedirectHandler): def redirect_request(self, req, fp, code, msg, headers, newurl): raise ManagedNotificationError("notification_redirect_rejected", 502) @@ -183,12 +187,18 @@ class ManagedNotifications: """One process-owned observer/worker; SQLite serializes other API processes.""" def __init__(self, directory: Path, *, transport: Callable = _https_request, clock: Callable = time.time, session_opener: Callable = open_profile_store, - observations: dict[str, Any] | None = None): + observations: dict[str, Any] | None = None, + send_on_queue: Callable[[Callable[[], None]], None] | None = None): if fcntl is None: raise ManagedNotificationError("notification_platform_unavailable", 503) self._fcntl = fcntl _private_directory(directory) self.directory, self.transport, self.clock = directory, transport, clock + # A new alert goes out from the process that queued it, on its own thread, + # instead of waiting for whichever Hermes process owns the sender to poll. + # Tests with an injected transport send only when they drain (or opt in). + self._send_on_queue = send_on_queue if send_on_queue is not None else ( + _send_in_background if transport is _https_request else None) self.session_opener = session_opener self.preference_policy: Callable | None = None # Live hook state. A fresh process starts empty; get_managed_notifications @@ -718,6 +728,7 @@ def _queue_event(self, profile: str, session_id: str, turn_id: str, event_type: content_text = self._rich_text(content_text) agent_name, avatar = self._agent_presentation(profile) now = int(self.clock()) + queued: list[str] = [] with self._db() as db: db.execute("BEGIN IMMEDIATE") rows = db.execute("SELECT g.* FROM grants g WHERE g.state='active' AND g.expires>? AND json_extract(g.public_json,'$.profile')=?", (now, profile)).fetchall() @@ -765,7 +776,12 @@ def _queue_event(self, profile: str, session_id: str, turn_id: str, event_type: due = now + _APPROVAL_GRACE_SECONDS if approval else now db.execute("INSERT INTO pending(intent_id,grant_id,path,raw,expires,state,next_attempt,session_ref) VALUES(?,?,?,?,?,'pending',?,?)", (event_id, grant["grantId"], "/events", raw, expires, due, reference)) + if not approval: + queued.append(event_id) self._wake.set() + # Approvals wait their grace period and stay with the sender that owns them. + if queued and self._send_on_queue is not None: + self._send_on_queue(lambda: self._send_now(queued)) def observe(self, hook: str, *, profile: str, **payload: Any): """Synchronous stock hook: persist only; never perform network I/O here.""" @@ -1056,33 +1072,49 @@ def drain_pending(self): rows = db.execute("SELECT p.* FROM pending p JOIN grants g USING(grant_id) WHERE p.state='pending' AND p.next_attempt<=? AND p.expires>? AND g.state='active' AND g.expires>? ORDER BY p.next_attempt,p.intent_id LIMIT 32", (now, now, now)).fetchall() for row in rows: if self._stop.is_set(): return - now = int(self.clock()) - with self._db() as db: - claimed = db.execute("UPDATE pending SET state='sending',next_attempt=? WHERE intent_id=? AND state='pending' AND expires>? AND EXISTS(SELECT 1 FROM grants WHERE grants.grant_id=pending.grant_id AND grants.state='active' AND grants.expires>?)", (now + 30, row["intent_id"], now, now)).rowcount - if claimed != 1: continue - try: - approval = row["path"] == "/events" and json.loads(bytes(row["raw"])).get("eventType") == _APPROVAL_EVENT - result = self._request("POST", row["grant_id"], row["path"], bytes(row["raw"]), - before_transport=(lambda: self._approval_transport_ready(row)) if approval else None) - if result.get("status") not in ("accepted", "duplicate") or not isinstance(result.get("deliveryId"), str): - raise ManagedNotificationError("notification_delivery_unconfirmed", 503) - except ManagedNotificationError as error: - if error.status in (403, 404): - self.remove(row["grant_id"]) - else: - with self._db() as db: - state = "failed" if error.status in (400, 401, 410, 422) else "pending" - # A post-hook/removal racing an in-flight failed request - # must not resurrect the retired intent. - db.execute("UPDATE pending SET state=?,attempts=attempts+1,next_attempt=? WHERE intent_id=? AND state='sending'", (state, now + min(60, 2 ** min(row["attempts"] + 1, 6)), row["intent_id"])) - if state == "failed": - db.execute("UPDATE approval_attention SET state='retired',reason='send_failed' WHERE event_id=? AND state='pending'", (row["intent_id"],)) - continue + self._send_row(row) + + def _send_now(self, intent_ids: list[str]): + """Sends alerts this process just queued. The claim below lets exactly one + sender (this one or the owner's drain) deliver each; approvals never come here.""" + now = int(self.clock()) + try: with self._db() as db: - db.execute("UPDATE pending SET state='accepted' WHERE intent_id=? AND state='sending'", (row["intent_id"],)) - if row["activity_id"] and json.loads(bytes(row["raw"])).get("phase") in ("completed", "failed"): - db.execute("UPDATE activities SET state='terminal_accepted' WHERE activity_id=? AND state='terminal_pending'", (row["activity_id"],)) + marks = ",".join("?" * len(intent_ids)) + rows = db.execute(f"SELECT p.* FROM pending p JOIN grants g USING(grant_id) WHERE p.intent_id IN ({marks}) AND p.state='pending' AND p.next_attempt<=? AND p.expires>? AND g.state='active' AND g.expires>? ORDER BY p.intent_id", (*intent_ids, now, now, now)).fetchall() + for row in rows: + if self._stop.is_set(): return + self._send_row(row) + except (ValueError, OSError, sqlite3.Error): + logger.warning("Managed notification immediate send unavailable; the sender retries") + def _send_row(self, row): + now = int(self.clock()) + with self._db() as db: + claimed = db.execute("UPDATE pending SET state='sending',next_attempt=? WHERE intent_id=? AND state='pending' AND expires>? AND EXISTS(SELECT 1 FROM grants WHERE grants.grant_id=pending.grant_id AND grants.state='active' AND grants.expires>?)", (now + 30, row["intent_id"], now, now)).rowcount + if claimed != 1: return + try: + approval = row["path"] == "/events" and json.loads(bytes(row["raw"])).get("eventType") == _APPROVAL_EVENT + result = self._request("POST", row["grant_id"], row["path"], bytes(row["raw"]), + before_transport=(lambda: self._approval_transport_ready(row)) if approval else None) + if result.get("status") not in ("accepted", "duplicate") or not isinstance(result.get("deliveryId"), str): + raise ManagedNotificationError("notification_delivery_unconfirmed", 503) + except ManagedNotificationError as error: + if error.status in (403, 404): + self.remove(row["grant_id"]) + else: + with self._db() as db: + state = "failed" if error.status in (400, 401, 410, 422) else "pending" + # A post-hook/removal racing an in-flight failed request + # must not resurrect the retired intent. + db.execute("UPDATE pending SET state=?,attempts=attempts+1,next_attempt=? WHERE intent_id=? AND state='sending'", (state, now + min(60, 2 ** min(row["attempts"] + 1, 6)), row["intent_id"])) + if state == "failed": + db.execute("UPDATE approval_attention SET state='retired',reason='send_failed' WHERE event_id=? AND state='pending'", (row["intent_id"],)) + return + with self._db() as db: + db.execute("UPDATE pending SET state='accepted' WHERE intent_id=? AND state='sending'", (row["intent_id"],)) + if row["activity_id"] and json.loads(bytes(row["raw"])).get("phase") in ("completed", "failed"): + db.execute("UPDATE activities SET state='terminal_accepted' WHERE activity_id=? AND state='terminal_pending'", (row["activity_id"],)) _instances: dict[str, ManagedNotifications] = {} _instances_lock = threading.Lock() diff --git a/plugin.yaml b/plugin.yaml index 4b71585..510d760 100644 --- a/plugin.yaml +++ b/plugin.yaml @@ -2,7 +2,7 @@ manifest_version: 1 name: loopdy label: Loopdy kind: platform -version: "2.18.1" +version: "2.18.2" license: Apache-2.0 description: > Native authenticated Hermes workspace controls, media voice, approvals, and diff --git a/tests/test_managed_approval_notifications.py b/tests/test_managed_approval_notifications.py index 227bb35..9f2917a 100644 --- a/tests/test_managed_approval_notifications.py +++ b/tests/test_managed_approval_notifications.py @@ -60,6 +60,14 @@ def test_human_approval_queues_exact_grant_owned_request_content(self): self.assertEqual(detail["content"]["text"], "PRIVATE description") self.assertNotIn("requestId", detail, "The observer did not supply a native request ID") + def test_approval_waits_for_its_owner_instead_of_sending_on_queue(self): + self.enroll_approval() + sent = [] + self.service._send_on_queue = lambda work: (sent.append(True), work()) + self.approval() + self.assertEqual(sent, []) + self.assertEqual(len(self.pending()), 1) + def test_old_completion_only_grant_does_not_authorize_approval(self): self.approval() self.assertEqual(self.pending(), []) diff --git a/tests/test_managed_notifications.py b/tests/test_managed_notifications.py index e166f06..06501b2 100644 --- a/tests/test_managed_notifications.py +++ b/tests/test_managed_notifications.py @@ -216,6 +216,16 @@ def test_unsubscribed_other_profile_children_and_cancellation_do_not_alert(self) def events_sent(self): return [json.loads(raw) for _, path, raw, _ in self.calls if path.endswith("/events")] + def test_a_reply_alert_goes_out_as_soon_as_it_is_queued(self): + # The process that ran the turn sends at once; waiting for the sender-owning + # Hermes process to poll made alerts late (5 s in older plugins). + self.service._send_on_queue = lambda work: work() + self.service.observe("post_llm_call",profile="default",session_id="desktop-chat",turn_id="turn-a",assistant_response="Done.") + self.assertEqual([e["content"]["text"] for e in self.events_sent()],["Done."]) + self.service.observe("on_session_end",profile="default",session_id="desktop-chat",turn_id="turn-a",completed=True,platform="desktop") + self.service.drain_pending() + self.assertEqual(len(self.events_sent()),1,"The regular sender never sends it again") + def test_profile_grant_alerts_for_a_chat_never_opened_on_the_phone(self): # Regression: alerts previously required a per-session row written only # when the phone opened that exact chat, so replies to chats started