diff --git a/loopdy_plugin/managed_notifications.py b/loopdy_plugin/managed_notifications.py index 17683e2..353b1d3 100644 --- a/loopdy_plugin/managed_notifications.py +++ b/loopdy_plugin/managed_notifications.py @@ -50,6 +50,8 @@ } _APPROVAL_EVENT = "approval.required" _CLARIFICATION_EVENT = "clarification.required" +# The messaging adapter presents a question just after the clarify tool hook saw it. +_ASKED_WINDOW_SECONDS = 600 _MAX_RICH_TEXT = 1_600 _MAX_AVATAR_BYTES = 524_288 _APPROVAL_GRACE_SECONDS = 3 @@ -218,6 +220,9 @@ def __init__(self, directory: Path, *, transport: Callable = _https_request, # Turns whose reply alert already went out from post_llm_call (setdefault: a # state dict made by an older copy of this module in the same process). self._alerted: OrderedDict[tuple[str, str, str], bool] = state.setdefault("alerted", OrderedDict()) + # Turns whose question alert already went out from the clarify tool hook, so the + # messaging adapter's own presentation of the same question isn't a second alert. + self._asked: OrderedDict[tuple[str, str, str], float] = state.setdefault("asked", OrderedDict()) self._child_owners: dict[tuple[str, str, str], str] = state["child_owners"] self._child_goals: dict[tuple[str, str, str], str] = state["child_goals"] self._key = self._identity() @@ -635,6 +640,31 @@ def _observe_approval(self, hook: str, *, profile: str, **payload: Any): self._queue_event(profile, session_id, turn_id, _APPROVAL_EVENT, tool_call_id=tool_call_id, content_text=content) + def _observe_question(self, profile: str, session_id: str, payload: dict[str, Any]): + """The agent asked a question with the clarify tool. + + Chats in the bighelp app run on the dashboard, where no adapter presents + the question, so this is the only place that sees it. Each question alerts + once, as it is asked; it is shown in the chat, not in the alert's actions. + """ + turn, call = payload.get("turn_id"), payload.get("tool_call_id") + if not isinstance(turn, str) or not _ID.fullmatch(turn): return + if not isinstance(call, str) or not _ID.fullmatch(call): return + question = _clarify_question(payload.get("args")) + if not question: return + try: + self._queue_event(profile, session_id, turn, _CLARIFICATION_EVENT, + event_key="tool:" + call, content_text=question) + except ManagedNotificationError: + # No avatar or no text: the question still waits in the chat. + logger.warning("Question notification unavailable") + return + with self._lock: + self._asked[(profile, session_id, turn)] = self.clock() + self._asked.move_to_end((profile, session_id, turn)) + while len(self._asked) > 256: + self._asked.popitem(last=False) + @staticmethod def _rich_text(value: Any) -> str: if isinstance(value, str): @@ -716,6 +746,9 @@ def publish_clarification(self, *, profile: str, session_id: str, turn_id: str, session_id = _identifier(session_id) turn_id = _identifier(turn_id) request_id = _identifier(request_id) + with self._lock: + if self._asked.get((profile, session_id, turn_id), 0) > self.clock() - _ASKED_WINDOW_SECONDS: + return self._session(profile, session_id) self._queue_event(profile, session_id, turn_id, _CLARIFICATION_EVENT, event_key=request_id, content_text=self._rich_text(question)) @@ -805,6 +838,8 @@ def _observe(self, hook: str, *, profile: str, **payload: Any): if not child_hook and (payload.get("parent_session_id") or payload.get("platform") == "subagent"): return with self._db() as db: if not db.execute("SELECT 1 FROM grants g WHERE g.state='active' AND g.expires>? AND json_extract(g.public_json,'$.profile')=?", (int(self.clock()), profile)).fetchone(): return + if hook == "pre_tool_call" and payload.get("tool_name") == "clarify" and not child_hook: + self._observe_question(profile, session_id, payload) turn = payload.get("turn_id") if hook == "post_llm_call" and isinstance(turn, str) and _ID.fullmatch(turn): coordinate = (profile, session_id, turn) @@ -1121,9 +1156,23 @@ def _send_row(self, row): _SHARED_OBSERVATIONS = "_loopdy_managed_notification_observations" +def _clarify_question(args: Any) -> str: + """What the clarify tool asks: one question, or the first of a batch.""" + if not isinstance(args, dict): return "" + questions = args.get("questions") + if isinstance(questions, list) and questions: + texts = [str((item.get("question") if isinstance(item, dict) else item) or "").strip() + for item in questions[:64]] + texts = [text for text in texts if text] + if not texts: return "" + return texts[0] if len(texts) == 1 else f"{texts[0]} (+{len(texts) - 1} more)" + question = args.get("question") + return question.strip() if isinstance(question, str) else "" + + def _new_observations() -> dict[str, Any]: return {"lock": threading.RLock(), "wake": threading.Event(), - "work": OrderedDict(), "responses": OrderedDict(), "alerted": OrderedDict(), + "work": OrderedDict(), "responses": OrderedDict(), "alerted": OrderedDict(), "asked": OrderedDict(), "child_owners": {}, "child_goals": {}, "loaded_profiles": set(), "approval_profiles": set(), "clarification_profiles": set()} diff --git a/tests/test_managed_question_notifications.py b/tests/test_managed_question_notifications.py new file mode 100644 index 0000000..365f271 --- /dev/null +++ b/tests/test_managed_question_notifications.py @@ -0,0 +1,107 @@ +from __future__ import annotations + +import json +import sqlite3 +import unittest +import uuid + +from typing import Any +from loopdy_plugin.managed_notifications import ManagedNotifications +if __package__: + from . import test_managed_notifications as fixtures +else: + import test_managed_notifications as fixtures + + +class ManagedQuestionNotificationTests(unittest.TestCase): + """A question the agent asks with the clarify tool alerts the phone. + + Chats in the bighelp app run on the dashboard, where the messaging adapter + never presents the question, so those questions used to send no alert. + """ + + service: ManagedNotifications + grant: dict[str, Any] + calls: list[tuple[str, str, bytes, dict[str, str]]] + now: int + setUp = fixtures.ManagedNotificationTests.setUp + tearDown = fixtures.ManagedNotificationTests.tearDown + get_session = fixtures.ManagedNotificationTests.get_session + transport = fixtures.ManagedNotificationTests.transport + + def enroll(self, event_types: list[str] | None = None): + self.grant_id = str(uuid.uuid4()) + self.grant = dict(self.grant, grantId=self.grant_id, eventTypes=event_types or [ + "session.completed", "session.failed", "approval.required", "clarification.required"]) + self.service.enroll(self.grant_id, str(uuid.uuid4())) + self.service.subscribe(self.grant_id, "default", "native-session", True) + self.service.producer_loaded("default", start_worker=False, clarification_producer_loaded=True) + self.calls.clear() + + def ask(self, args: Any, *, tool: str = "clarify", call: str = "toolu_01question", **changes: Any): + payload = dict(profile="default", session_id="native-session", turn_id="turn-a", + tool_call_id=call, tool_name=tool, args=args) + payload.update(changes) + self.service.observe("pre_tool_call", **payload) + + def pending(self): + with sqlite3.connect(self.service.db_path) as db: + return [json.loads(row[0]) for row in db.execute( + "SELECT raw FROM pending WHERE state='pending' AND grant_id=? AND path='/events'", + (self.grant_id,))] + + def detail(self, row: dict[str, Any]) -> dict[str, Any]: + return self.service.event(self.grant_id, row["eventId"])["event"] + + def test_a_question_in_an_app_chat_alerts_once(self): + self.enroll() + self.ask({"question": "Which city should I book?", "choices": ["Austin", "Denver"]}) + self.ask({"question": "Which city should I book?", "choices": ["Austin", "Denver"]}) + rows = self.pending() + self.assertEqual(len(rows), 1) + self.assertEqual(rows[0]["eventType"], "clarification.required") + detail = self.detail(rows[0]) + self.assertEqual(detail["content"], {"kind": "clarification", "text": "Which city should I book?"}) + self.assertEqual((detail["sessionId"], detail["turnId"]), ("native-session", "turn-a")) + + def test_each_question_in_a_turn_alerts(self): + self.enroll() + self.ask({"question": "First?"}, call="toolu_01first") + self.ask({"question": "Second?"}, call="toolu_01second") + self.assertEqual([self.detail(row)["content"]["text"] for row in self.pending()], ["First?", "Second?"]) + + def test_a_batch_leads_with_its_first_question(self): + self.enroll() + self.ask({"questions": [{"question": "Which city?"}, {"question": "Which dates?"}, "Budget?"]}) + self.assertEqual(self.detail(self.pending()[0])["content"]["text"], "Which city? (+2 more)") + + def test_other_tools_and_empty_questions_send_nothing(self): + self.enroll() + self.ask({"command": "ls"}, tool="terminal") + self.ask({"question": " "}) + self.ask("not arguments") + self.ask({"questions": []}) + self.ask({"question": "Which city?"}, turn_id="") + self.ask({"question": "Which city?"}, call="") + self.assertEqual(self.pending(), []) + + def test_a_grant_without_questions_sends_nothing(self): + self.enroll(["session.completed", "session.failed"]) + self.ask({"question": "Which city should I book?"}) + self.assertEqual(self.pending(), []) + + def test_a_subagents_question_belongs_to_its_parent_and_sends_nothing_itself(self): + self.enroll() + self.ask({"question": "Which city?"}, parent_session_id="native-session", session_id="child-session") + self.assertEqual(self.pending(), []) + + def test_the_messaging_adapter_does_not_alert_the_same_question_again(self): + self.enroll() + self.ask({"question": "Which city should I book?"}) + self.service.publish_clarification(profile="default", session_id="native-session", turn_id="turn-a", + request_id="clarify-1", question="Which city should I book?") + self.assertEqual(len(self.pending()), 1) + + +if __name__ == "__main__": + unittest.main()