From f36091672a1dfb97818c60181aa43db220e681bb Mon Sep 17 00:00:00 2001 From: GordieBox Date: Wed, 11 Nov 2026 18:09:13 -0600 Subject: [PATCH 1/2] Live Activity updates carry the step in progress, sealed for the phone A phone gives the host a key for a chat's row over its own connection. Each update for that card then carries sealed detail: the step in progress, the last steps, a question that waits, the reply's first lines. The notification service and Apple forward bytes they cannot read. A new step alone goes at low priority. Co-Authored-By: Claude Fable 5.2 --- AGENTS.md | 2 +- docs/NOTIFICATIONS.md | 27 ++- docs/SECURITY_AND_PRIVACY.md | 9 +- fixtures/contracts/sealed-card-v1-vector.json | 35 ++++ loopdy_plugin/card_detail.py | 170 ++++++++++++++++++ loopdy_plugin/managed_notifications.py | 106 +++++++++-- loopdy_plugin/managed_notifications_api.py | 9 + loopdy_plugin/registration.py | 7 + tests/test_card_detail.py | 142 +++++++++++++++ 9 files changed, 490 insertions(+), 17 deletions(-) create mode 100644 fixtures/contracts/sealed-card-v1-vector.json create mode 100644 loopdy_plugin/card_detail.py create mode 100644 tests/test_card_detail.py diff --git a/AGENTS.md b/AGENTS.md index 81c5a0b..ab9eee0 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -79,7 +79,7 @@ Many features span both repos. The app's side of each route lives in the app rep | `loopdy_plugin/agent_guide.py`, `skills/bighelp/` | What agents are told about bighelp: the chat brief and the `bighelp` skill | | `loopdy_plugin/agent_board.py`, `provider_usage.py`, `secure_input.py`, `agent_templates.py`, `reactions.py` | Feature modules | | `loopdy_plugin/live_voice_*.py`, `native_voice.py` | Live voice | -| `loopdy_plugin/managed_notifications*.py`, `sealed_alerts.py`, `notification_crypto.py` | Notifications and Live Activities | +| `loopdy_plugin/managed_notifications*.py`, `sealed_alerts.py`, `card_detail.py`, `notification_crypto.py` | Notifications and Live Activities (`card_detail.py`: what a card shows beyond its phase, sealed for the phone) | | `loopdy_plugin/plugin_update*.py`, `host_restart.py` | Self-update and the in-place restart | | `loopdy_plugin/store.py` | The local store for card templates, form answers, approvals and events (`get_service()` in `adapter.py`) | | `loopdy_plugin/adapter.py`, `service.py`, `provider.py`, `providers/` | The `loopdy` gateway platform and the legacy push provider, kept only for older setups | diff --git a/docs/NOTIFICATIONS.md b/docs/NOTIFICATIONS.md index 894318d..d77c00a 100644 --- a/docs/NOTIFICATIONS.md +++ b/docs/NOTIFICATIONS.md @@ -371,8 +371,31 @@ older plugin is marked failed and never sent. The app starts the Live Activity itself. The host then sends updates for the current turn through the same grant (`PUT/DELETE /notifications/enrollments//live-activities/`). Updates carry only a -phase, a fixed label such as "Your agent is working" or "Your agent finished", and counts. They never include -message text. +phase, a fixed label such as "Your agent is working" or "Your agent finished", and counts. The notification +service and Apple can read these. They never include message text. + +### Sealed card detail + +An app that shows more on the card gives the host a key for that chat's row +(`PUT /notifications/enrollments//live-activities//card-key`, body +`{"version": 1, "key": "<32 bytes, base64url>"}`). The key comes over the app's own connection to this host, +never through the notification service. `capabilities` lists `sealedCardDetail: {"version": 1}`. + +From then on each update for that card also carries `sealed`: the step in progress and what it works on, the +last three steps, the model's latest words between steps, a question or command that waits for the person, the +reply's first lines when the turn ends, helper goals, context use and the model's name. It is AES-256-GCM under +the row key, bound to the update's timestamp, and at most 1,200 characters. The service keeps and forwards the +bytes and cannot read them. A note that could hold a credential is left out. The format is in +[`card_detail.py`](../loopdy_plugin/card_detail.py), and `fixtures/contracts/sealed-card-v1-vector.json` is +shared with the app's tests. + +A card with detail gets an update for each new step, at most one every 8 seconds. A new step alone is sent +with `quiet: true`, which the service sends at low priority, except that one update in every 30 seconds is not +quiet. A question, a command that waits for approval and the end of the turn go at once. A chat without a key +gets the updates it always got, 30 seconds apart. If the service refuses an update that has `sealed`, the host +drops that card's key and sends plain updates. + +While the agent asks a question with `clarify`, or a command waits for approval, the card's phase is `waiting`. ## Host storage diff --git a/docs/SECURITY_AND_PRIVACY.md b/docs/SECURITY_AND_PRIVACY.md index f8a3669..2ca907e 100644 --- a/docs/SECURITY_AND_PRIVACY.md +++ b/docs/SECURITY_AND_PRIVACY.md @@ -38,9 +38,12 @@ The host never sends an alert it can't seal: until the phone has registered its builds do right after turning notifications on, no alert is queued or sent. App builds before bighelp 2.3.0 (20) never register a key, so they get no alerts. -Live Activity updates contain only a phase, a fixed label and counts, never message text. The Lock Screen can -still show the agent and chat name the app put on the activity; turn off Live Activities or notification -previews in iOS settings if that matters to you. +Live Activity updates contain a phase, a fixed label and counts that the notification service and Apple can +read, never message text. For an app that asks for it, an update also carries detail (the step in progress, a +question that waits, the reply's first lines) encrypted with a key that only that phone and this host hold; the +service and Apple forward bytes they cannot read (see [Notifications](NOTIFICATIONS.md#sealed-card-detail)). The +Lock Screen shows what the app draws from it, with the agent and chat name; choose how much in the app's +Settings › Notifications, or turn off Live Activities in iOS settings if that matters to you. ## Cards diff --git a/fixtures/contracts/sealed-card-v1-vector.json b/fixtures/contracts/sealed-card-v1-vector.json new file mode 100644 index 0000000..7632482 --- /dev/null +++ b/fixtures/contracts/sealed-card-v1-vector.json @@ -0,0 +1,35 @@ +{ + "comment": "sealed-card-v1: AES-256-GCM, blob = nonce(12)+ciphertext+tag(16) in unpadded base64url, AAD = 'bighelp-card-v1|' + timestamp. Shared by the plugin's card_detail.py and the app's BighelpActivityDetail. Made-up data.", + "key": "AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8", + "nonce": "ZGVmZ2hpamtsbW5v", + "timestamp": 1800000123, + "detail": { + "v": 1, + "b": 1800000000, + "s": 9, + "t": "execute_code", + "n": "price per lb", + "tr": [ + { + "t": "web_extract", + "c": 6, + "n": "example.com" + }, + { + "t": "web_search", + "c": 3, + "n": "protein powder prices" + } + ], + "say": "Comparing four brands now.", + "h": [ + "Check shipping costs" + ], + "cu": 30300, + "cm": 272000, + "m": "sample-model-1", + "q": "Send the order for $47.00?", + "p": "Cheapest per lb is Northfield Whey at $9.40 — “four” brands compared." + }, + "sealed": "ZGVmZ2hpamtsbW5vMzm8REPYbq4OUm_Y6lVa0WChayixXsRAl-GcZNnA0Gqu2nDzfCK3JpXRQmTfAaKqeDC4lEgjMViTn8v2jO7W_nuuhiL0Jhk_qRyMLmHmVMsJF3tRy-i85PPTWOZBMT4j5xL3Xhsoyl7fmPzpgH2a0gBo6HqgCdxHxlnj1KiUZKUS9uuIJ10wX6EvP2Dl5HzV_qKEZjE_prYIv0p9wPMlbrDTp8D2s5SSidg8144GwqDygu3KWN4irgpkdWbgrD2_6BUkuc17ECE2Fw5DKkiWbTJo8G31eCiJxTYy5NPHPck9BZjCjqdYX2OOZvPrOu2hMaRuxZTki6SygjoJUF-U_wRT5O8KB7b6n3z0vtrDZnXL_jlP-lwfAbxhanAbCGZJiI83CFpfi8RC9nSm0ZKuymphN4xnZiG1OPVMbvTqTl7FM7KUY3xjjeGsIUi2AkVGldI4E6dsz-KWptnpW9OnePr0uekMckrYwePdhj92y1QkvYZtvbGK1VlkmtlKqYrJAEJjaMKx-gPuzr8rT9W-IvFxGhvqvwrnjg" +} \ No newline at end of file diff --git a/loopdy_plugin/card_detail.py b/loopdy_plugin/card_detail.py new file mode 100644 index 0000000..c5629f8 --- /dev/null +++ b/loopdy_plugin/card_detail.py @@ -0,0 +1,170 @@ +"""What a Live Activity row shows beyond its phase, sealed for the phone (sealed-card-v1). + +The notification service and Apple read a row's phase, time and helper count. Everything +else (the step in progress, the last steps, a question, the reply's first lines) goes in +`sealed`, which only the phone opens. The phone gives this host one key per chat row over +its own connection, never through the notification service. + +Format: unpadded base64url of nonce(12) + AES-256-GCM(JSON) + tag(16). +AAD: "bighelp-card-v1|" + the update's timestamp, which is the row's timestamp on the phone, +so a blob cannot be shown with another update's time. +The JSON's keys are short because five rows share one 4 KB push: + v 1 · b turn start · s steps so far · t tool in progress · n its note + tr last finished steps, newest first: {t tool, c how many in a row, n note} + say the model's latest words between steps · q the question that waits + p the reply's first lines · h helper goals · cu/cm context tokens used/window · m model +The phone words the steps itself from the tool names (it has the translations). +`fixtures/contracts/sealed-card-v1-vector.json` is shared with the app's opener. +""" +from __future__ import annotations + +import hashlib +import json +import os +from typing import Any +from urllib.parse import urlsplit + +from cryptography.hazmat.primitives.ciphers.aead import AESGCM + +from .notification_crypto import b64url_decode, b64url_encode +from .sensitive import contains_sensitive_credential + +VERSION = 1 +KEY_BYTES = 32 +# What the notification service takes for one row. +MAX_SEALED_CHARS = 1_200 +# (840 + 28) bytes are 1,158 base64url characters. +_MAX_PLAINTEXT_BYTES = 840 +_AAD_LABEL = "bighelp-card-v1|" +_TRAIL = 3 + + +def key_from(value: Any) -> bytes | None: + """The row key a phone sent, or None when it is not 32 bytes of base64url.""" + if not isinstance(value, str) or len(value) != 43: return None + try: + key = b64url_decode(value) + except ValueError: + return None + return key if len(key) == KEY_BYTES else None + + +def new_detail(started: int) -> dict[str, Any]: + return {"started": int(started), "steps": 0, "tool": "", "note": "", "trail": [], "say": "", + "question": "", "preview": "", "goals": {}, "used": None, "window": None, "model": ""} + + +def _line(value: Any, limit: int) -> str: + """One bounded line of text, or nothing when it could carry a credential.""" + if not isinstance(value, str): return "" + text = " ".join(value.split()) + if not text or contains_sensitive_credential(text): return "" + return text if len(text) <= limit else text[:limit - 1].rstrip() + "…" + + +def _site(value: Any) -> str: + if isinstance(value, list): value = value[0] if value else "" + if not isinstance(value, str): return "" + host = urlsplit(value if "//" in value else "//" + value).hostname or "" + return _line(host.removeprefix("www."), 60) + + +def _note(tool: str, args: Any) -> str: + """A few words on what this step works on. Never a whole argument list.""" + if not isinstance(args, dict): return "" + name = tool.lower() + if "search" in name: return _line(args.get("query") or args.get("pattern"), 80) + if "web_extract" in name or "browser" in name or "fetch" in name: + return _site(args.get("url") or args.get("urls")) + if "terminal" in name: return _line((args.get("command") or "").split("\n")[0] if isinstance(args.get("command"), str) else "", 60) + if "file" in name or name == "patch": + path = args.get("path") or args.get("file_path") + return _line(os.path.basename(path), 60) if isinstance(path, str) else "" + if "delegate" in name: return _line(args.get("goal"), 80) + if "image" in name: return _line(args.get("prompt"), 80) + if "skill" in name: return _line(args.get("name"), 60) + return "" + + +def tool_started(detail: dict[str, Any], tool: Any, args: Any) -> None: + if not isinstance(tool, str) or not tool: return + detail["steps"] = min(detail["steps"] + 1, 9_999) + detail["tool"], detail["note"] = tool[:48], _note(tool, args) + + +def tool_finished(detail: dict[str, Any], tool: Any, args: Any) -> None: + if not isinstance(tool, str) or not tool: return + tool, trail = tool[:48], detail["trail"] + note = detail["note"] if detail["tool"] == tool else _note(tool, args) + if trail and trail[0]["t"] == tool: + trail[0]["c"] = min(trail[0]["c"] + 1, 999) + if note: trail[0]["n"] = note + else: + trail.insert(0, {"t": tool, "c": 1, **({"n": note} if note else {})}) + del trail[_TRAIL:] + if detail["tool"] == tool: detail["tool"], detail["note"] = "", "" + + +def model_answered(detail: dict[str, Any], payload: dict[str, Any]) -> None: + """One model request ended (Hermes' post_api_request): its words, the context it used, its model.""" + message = payload.get("assistant_message") + content = getattr(message, "content", None) + if isinstance(message, dict): content = message.get("content") + if isinstance(content, list): + content = " ".join(str(part.get("text", "")) for part in content if isinstance(part, dict)) + said = _line(content, 160) + if said: detail["say"] = said + usage, window = payload.get("usage"), payload.get("context_length") + used = usage.get("prompt_tokens") if isinstance(usage, dict) else None + if type(used) is int and used > 0: detail["used"] = used + if type(window) is int and window > 0: detail["window"] = window + model = payload.get("response_model") or payload.get("model") + if isinstance(model, str) and model: detail["model"] = _line(model.rsplit("/", 1)[-1], 48) + + +def plaintext(detail: dict[str, Any], phase: str) -> bytes: + """The row's JSON, cut down until it fits one row's share of a push.""" + body: dict[str, Any] = {"v": VERSION, "b": detail["started"], "s": detail["steps"]} + terminal = phase in ("completed", "failed") + if detail["tool"] and not terminal: + body["t"] = detail["tool"] + if detail["note"]: body["n"] = detail["note"] + if detail["trail"]: body["tr"] = [dict(step) for step in detail["trail"]] + if detail["say"] and not terminal: body["say"] = detail["say"] + if phase == "waiting" and detail["question"]: body["q"] = _line(detail["question"], 200) + if terminal and detail["preview"]: body["p"] = _line(detail["preview"], 280) + goals = [goal for goal in detail["goals"].values() if goal][:2] + if goals and not terminal: body["h"] = goals + if detail["used"] and detail["window"]: body["cu"], body["cm"] = detail["used"], detail["window"] + if detail["model"]: body["m"] = detail["model"] + + def encoded() -> bytes: + return json.dumps(body, ensure_ascii=False, separators=(",", ":"), sort_keys=True).encode() + # Drop what matters least first; the question and the reply's lines go last, and shorter. + for cut in ("h", "say", "m", "n"): + if len(encoded()) <= _MAX_PLAINTEXT_BYTES: break + body.pop(cut, None) + if len(encoded()) > _MAX_PLAINTEXT_BYTES: + for step in body.get("tr", []): step.pop("n", None) + for key in ("p", "q"): + while len(encoded()) > _MAX_PLAINTEXT_BYTES and len(body.get(key, "")) > 40: + body[key] = body[key][:len(body[key]) // 2].rstrip() + "…" + return encoded() + + +def digest(plain: bytes) -> str: + """Stands for the detail in an update's signature, so a new step counts as a change.""" + return hashlib.sha256(plain).hexdigest()[:16] + + +def seal(key: bytes, timestamp: int, plain: bytes, *, nonce: bytes | None = None) -> str: + nonce = nonce or os.urandom(12) + sealed = b64url_encode(nonce + AESGCM(key).encrypt(nonce, plain, (_AAD_LABEL + str(int(timestamp))).encode())) + if len(sealed) > MAX_SEALED_CHARS: raise ValueError("sealed card detail is too large") + return sealed + + +def open_sealed(key: bytes, timestamp: int, sealed: str) -> dict[str, Any]: + """What the phone does. Here for tests and the shared vector.""" + raw = b64url_decode(sealed) + return json.loads(AESGCM(key).decrypt(raw[:12], raw[12:], (_AAD_LABEL + str(int(timestamp))).encode())) diff --git a/loopdy_plugin/managed_notifications.py b/loopdy_plugin/managed_notifications.py index 6d9d30d..fc2f380 100644 --- a/loopdy_plugin/managed_notifications.py +++ b/loopdy_plugin/managed_notifications.py @@ -34,6 +34,7 @@ from cryptography.hazmat.primitives import serialization from cryptography.hazmat.primitives.asymmetric import ec +from . import card_detail from . import host_telemetry from . import live_alerts from . import notification_channels @@ -88,6 +89,9 @@ _APPROVAL_LIMIT = 4096 _APPROVAL_HOOKS = ("pre_approval_request", "post_approval_response") _ACTIVITY_REFRESH_SECONDS = 60 +# Seconds between a card's updates while it carries sealed detail, and between its high-priority ones. +_DETAIL_SPACING = 8 +_LOUD_SPACING = 30 # A rotating sign-in (the Nous Portal's lasts a day) runs out if bighelp stays closed. # Waking the phone this often gives it more than one chance to renew before then. _SIGN_IN_WAKE_SECONDS = 8 * 3600 @@ -411,6 +415,11 @@ def __init__(self, directory: Path, *, transport: Callable = _https_request, CREATE TABLE IF NOT EXISTS quiet_hours(grant_id TEXT PRIMARY KEY REFERENCES grants(grant_id) ON DELETE CASCADE, enabled INTEGER NOT NULL, start_minute INTEGER NOT NULL, end_minute INTEGER NOT NULL, time_zone TEXT NOT NULL); CREATE TABLE IF NOT EXISTS activities(activity_id TEXT PRIMARY KEY, grant_id TEXT NOT NULL REFERENCES grants(grant_id) ON DELETE CASCADE, profile TEXT NOT NULL, session_id TEXT NOT NULL, session_ref TEXT NOT NULL, lease_expires INTEGER NOT NULL, work_turn TEXT, state TEXT NOT NULL, last_timestamp INTEGER NOT NULL DEFAULT 0, last_signature TEXT, last_queued_at INTEGER NOT NULL DEFAULT 0); """) + # Added for sealed card detail: the chat row's key from the phone, and when an + # update last went out at high priority. + columns = {row[1] for row in db.execute("PRAGMA table_info(activities)")} + if "card_key" not in columns: db.execute("ALTER TABLE activities ADD COLUMN card_key BLOB") + if "last_loud_at" not in columns: db.execute("ALTER TABLE activities ADD COLUMN last_loud_at INTEGER NOT NULL DEFAULT 0") db.executescript(live_alerts.SCHEMA) db.executescript(scheduled_links.SCHEMA) @@ -462,7 +471,8 @@ def capabilities(self) -> dict[str, Any]: "managedEnrollmentSupported": True, "supportedEventTypes": sorted(_EVENT_TYPES), "sealedAlerts": {"version": 2}, "preferences": {"peerChats": True, "workflows": True, "scheduledLinks": True, "channels": True, "kinds": True}, - "richLiveActivitySupported": True, "producerCapabilities": { + "richLiveActivitySupported": True, "sealedCardDetail": {"version": card_detail.VERSION}, + "producerCapabilities": { "sessionCompletion": loaded, "sessionFailure": loaded, "richLiveActivity": loaded, "nativeApproval": approval_loaded, "nativeClarification": clarification_loaded}} @@ -882,9 +892,30 @@ def subscribe_activity(self, grant_id: str, activity_id: str, profile: str, sess # Terminal pending/accepted retries keep their original frozen request. if work is not None: phase, count, terminal = self._work_projection(work) - self._queue_activity(profile, session_id, work["turn"], phase, count, terminal, stopped=work["outcome"] == "cancelled" and terminal) + self._queue_activity(profile, session_id, work["turn"], phase, count, terminal, stopped=work["outcome"] == "cancelled" and terminal, detail=work.get("detail")) return {"version": 1, "activityId": activity_id, "grantId": grant_id, "sessionReference": reference, "state": "subscribed"} + def set_card_key(self, grant_id: str, activity_id: str, key: Any): + """The phone's key for this chat row's sealed detail (card_detail.py). + + It comes over the phone's own connection to this host. The next update for + the card carries the detail, so the card fills in at once. + """ + self._grant(grant_id); _identifier(activity_id) + secret = card_detail.key_from(key) + if secret is None: raise ManagedNotificationError("notification_card_key_invalid", 400) + with self._lock: + with self._db() as db: + row = db.execute("SELECT profile,session_id,work_turn FROM activities WHERE activity_id=? AND grant_id=?", (activity_id, grant_id)).fetchone() + if not row: raise ManagedNotificationError("notification_activity_unknown", 404) + db.execute("UPDATE activities SET card_key=?,last_signature=NULL WHERE activity_id=?", (secret, activity_id)) + work = self._work.get((row["profile"], row["session_id"], row["work_turn"])) if row["work_turn"] else None + if work is not None and not work["terminal"]: + phase, count, terminal = self._work_projection(work) + self._queue_activity(row["profile"], row["session_id"], work["turn"], phase, count, terminal, + detail=work.get("detail"), at_once=True) + return {"version": 1, "activityId": activity_id, "grantId": grant_id, "state": "sealed"} + def remove_activity(self, grant_id: str, activity_id: str): self._grant(grant_id); _identifier(activity_id) with self._db() as db: @@ -1399,9 +1430,12 @@ def _observe(self, hook: str, *, profile: str, **payload: Any): stage_session if isinstance(stage_session, str) else "", payload.get("user_message") if hook == "pre_llm_call" else None): return if hook in _APPROVAL_HOOKS: - self._observe_approval(hook, profile=profile, **payload) + try: + self._observe_approval(hook, profile=profile, **payload) + finally: + self._observe_card_approval(hook, profile, payload) return - if hook not in ("pre_llm_call", "post_llm_call", "pre_tool_call", "post_tool_call", + if hook not in ("pre_llm_call", "post_llm_call", "pre_tool_call", "post_tool_call", "post_api_request", "on_session_end", "subagent_start", "subagent_stop"): return profile = _identifier(payload.get("profile_name") or profile, _PROFILE) @@ -1518,10 +1552,12 @@ def _observe(self, hook: str, *, profile: str, **payload: Any): self._child_owners.pop(child_key, None) self._child_goals.pop(child_key, None) work = {"turn": turn, "phase": "thinking", "outcome": None, "children": {}, "terminal": False, - "observed_at": int(self.clock())} + "observed_at": int(self.clock()), "detail": card_detail.new_detail(int(self.clock()))} self._work[coordinate] = work elif work["terminal"]: return if work is None or work["terminal"]: return + # A turn observed before this plugin version loaded has none yet. + work.setdefault("detail", card_detail.new_detail(work["observed_at"])) if child_hook: child = payload.get("child_session_id") or payload.get("child_subagent_id") parent_turn = payload.get("parent_turn_id") @@ -1539,9 +1575,12 @@ def _observe(self, hook: str, *, profile: str, **payload: Any): self._child_goals.setdefault(owner_key, goal[:400]) # A repeated start after stop cannot resurrect this child. work["children"].setdefault(child, "active") + if work["children"][child] == "active" and isinstance(goal, str) and goal: + work["detail"]["goals"][child] = card_detail._line(goal, 60) else: if self._child_owners.get(owner_key) != work["turn"] or work["children"].get(child) != "active": return work["children"][child] = "ended" + work["detail"]["goals"].pop(child, None) status = payload.get("child_status") goal = payload.get("child_goal") if not isinstance(goal, str) or not " ".join(goal.split()): @@ -1568,7 +1607,18 @@ def _observe(self, hook: str, *, profile: str, **payload: Any): else: return elif hook == "post_llm_call": work["phase"] = "responding" - elif hook in ("pre_tool_call", "post_tool_call"): + work["detail"]["preview"] = self._responses.get((profile, session_id, turn), "") + elif hook == "post_api_request": + # One model request of the turn ended. The phase is the tool hooks' to set. + card_detail.model_answered(work["detail"], payload) + elif hook == "pre_tool_call": + card_detail.tool_started(work["detail"], payload.get("tool_name"), payload.get("args")) + question = _clarify_question(payload.get("args")) if payload.get("tool_name") == "clarify" else "" + work["detail"]["question"] = question + work["phase"] = "waiting" if question else "using_tool" + elif hook == "post_tool_call": + card_detail.tool_finished(work["detail"], payload.get("tool_name"), payload.get("args")) + work["detail"]["question"] = "" work["phase"] = "using_tool" work["observed_at"] = int(self.clock()) phase, active_count, terminal = self._work_projection(work) @@ -1576,16 +1626,37 @@ def _observe(self, hook: str, *, profile: str, **payload: Any): # Rich-v1 uses completed as the terminal transport state. Stopped # remains explicit fixed copy; cancellation never queues an alert. self._queue_activity(profile, session_id, work["turn"], phase, active_count, terminal, - allow_bind=hook == "pre_llm_call", stopped=work["outcome"] == "cancelled" and terminal) + allow_bind=hook == "pre_llm_call", stopped=work["outcome"] == "cancelled" and terminal, + detail=work["detail"]) + + def _observe_card_approval(self, hook: str, profile: str, payload: dict[str, Any]): + """A command waits for the person's yes: the card says so until they answer.""" + if payload.get("surface") != "gateway" or payload.get("parent_session_id"): return + session_id, turn = payload.get("session_id"), payload.get("turn_id") + if not isinstance(session_id, str) or not isinstance(turn, str): return + with self._lock: + work = self._work.get((profile, session_id, turn)) + if work is None or work["terminal"] or work["outcome"] is not None: return + asking = hook == "pre_approval_request" + work["detail"]["question"] = self._rich_text(payload.get("description") or payload.get("command")) if asking else "" + work["phase"] = "waiting" if asking else "using_tool" + phase, active_count, terminal = self._work_projection(work) + self._queue_activity(profile, session_id, turn, phase, active_count, terminal, detail=work["detail"]) - def _queue_activity(self, profile: str, session_id: str, turn: str, phase: str, count: int, terminal: bool, *, allow_bind: bool = False, stopped: bool = False): + def _queue_activity(self, profile: str, session_id: str, turn: str, phase: str, count: int, terminal: bool, *, + allow_bind: bool = False, stopped: bool = False, detail: dict[str, Any] | None = None, + at_once: bool = False): now = int(self.clock()) with self._db() as db: rows = db.execute("SELECT a.*,g.expires AS grant_expires FROM activities a JOIN grants g USING(grant_id) WHERE a.profile=? AND a.session_id=? AND a.state='active' AND a.lease_expires>? AND g.state='active' AND g.expires>?", (profile, session_id, now, now)).fetchall() for row in rows: if row["work_turn"] not in (None, turn) or (row["work_turn"] is None and not allow_bind): continue action = "Stopped" if stopped and terminal and phase == "completed" else _ACTIONS[phase] - signature = json.dumps([turn, phase, count, action]) + # With the phone's key for this row, the update also carries the sealed detail. + key = bytes(row["card_key"]) if row["card_key"] else None + plain = card_detail.plaintext(detail, phase) if key and detail else None + status = json.dumps([turn, phase, count, action]) + signature = status if plain is None else json.dumps([turn, phase, count, action, card_detail.digest(plain)]) # A real hook re-sends an unchanged state once a minute, inside the # 120-second stale window, so a long run of tool calls stays current. if row["last_signature"] == signature and row["last_queued_at"] > now - _ACTIVITY_REFRESH_SECONDS: continue @@ -1598,11 +1669,21 @@ def _queue_activity(self, profile: str, session_id: str, turn: str, phase: str, update = {"version": 2, "updateId": update_id, "sessionReference": row["session_ref"], "phase": phase, "currentAction": action, "progress": 100 if terminal else 0, "completedSteps": 0, "activeSubagentCount": count, "latestTool": None, "timestamp": timestamp, "expires": expires} - due = now if terminal or phase == "waiting" else max(now, pending["next_attempt"] if pending else row["last_queued_at"] + 30) + urgent = terminal or phase == "waiting" or at_once + # A card with detail changes with each step, so its updates go _DETAIL_SPACING apart, not 30 s. + due = now if urgent else max(now, pending["next_attempt"] if pending else row["last_queued_at"] + (_DETAIL_SPACING if plain else 30)) + loud = True + if plain is not None: + update["sealed"] = card_detail.seal(key, timestamp, plain) + # Apple limits high-priority card updates. A new step alone goes at low priority, + # except that one update every _LOUD_SPACING is high, so a locked phone keeps up. + same_status = (row["last_signature"] or "").startswith(status[:-1] + ",") + loud = urgent or not same_status or due - row["last_loud_at"] >= _LOUD_SPACING + if not loud: update["quiet"] = True # Only nonterminal updates may be superseded; terminal is durable. db.execute("DELETE FROM pending WHERE activity_id=? AND state='pending'", (row["activity_id"],)) db.execute("INSERT INTO pending(intent_id,grant_id,path,raw,expires,state,next_attempt,session_ref,activity_id) VALUES(?,?,?,?,?,'pending',?,?,?)", (update_id, row["grant_id"], "/live-activities/" + row["activity_id"] + "/updates", canonical_json_bytes(update), expires, due, row["session_ref"], row["activity_id"])) - db.execute("UPDATE activities SET work_turn=?,state=?,last_timestamp=?,last_signature=?,last_queued_at=? WHERE activity_id=?", (turn, "terminal_pending" if terminal else "active", timestamp, signature, due, row["activity_id"])) + db.execute("UPDATE activities SET work_turn=?,state=?,last_timestamp=?,last_signature=?,last_queued_at=?,last_loud_at=? WHERE activity_id=?", (turn, "terminal_pending" if terminal else "active", timestamp, signature, due, due if loud else row["last_loud_at"], row["activity_id"])) host_telemetry.alert_queued(event_type="liveactivity", queue_ms=max(0, due - now) * 1000) self._wake.set() @@ -1848,6 +1929,9 @@ def _send_row(self, row): else: with self._db() as db: state = "failed" if error.status in (400, 401, 410, 422) else "pending" + if error.status == 400 and row["activity_id"] and b'"sealed"' in bytes(row["raw"]): + # A notification service that does not take sealed detail: the card goes on with its status. + db.execute("UPDATE activities SET card_key=NULL,last_signature=NULL WHERE activity_id=?", (row["activity_id"],)) # 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"])) diff --git a/loopdy_plugin/managed_notifications_api.py b/loopdy_plugin/managed_notifications_api.py index c5dc08f..6992621 100644 --- a/loopdy_plugin/managed_notifications_api.py +++ b/loopdy_plugin/managed_notifications_api.py @@ -82,6 +82,10 @@ class ActivityBody(VersionedBody): turnId: str | None = Field(default=None, pattern=_ID) +class CardKeyBody(VersionedBody): + key: str = Field(pattern=r"^[A-Za-z0-9_-]{43}$") + + def _call(operation, *args): try: return operation(*args) @@ -175,6 +179,11 @@ def activity(grant_id: str, activity_id: str, body: ActivityBody): return _call(lambda: get_managed_notifications().subscribe_activity(grant_id, activity_id, body.profile, body.sessionId, body.sessionReference, body.leaseExpires, body.turnId)) +@router.put("/enrollments/{grant_id}/live-activities/{activity_id}/card-key") +def activity_card_key(grant_id: str, activity_id: str, body: CardKeyBody): + return _call(lambda: get_managed_notifications().set_card_key(grant_id, activity_id, body.key)) + + @router.delete("/enrollments/{grant_id}/live-activities/{activity_id}") def remove_activity(grant_id: str, activity_id: str): return _call(lambda: get_managed_notifications().remove_activity(grant_id, activity_id)) diff --git a/loopdy_plugin/registration.py b/loopdy_plugin/registration.py index 687c656..059b785 100644 --- a/loopdy_plugin/registration.py +++ b/loopdy_plugin/registration.py @@ -215,6 +215,13 @@ def observe_managed(hook, **payload): for hook in ("pre_llm_call", "post_llm_call", "pre_tool_call", "post_tool_call", "on_session_end", "subagent_start", "subagent_stop"): _register_notification_observer(ctx, hook, partial(observe_managed, hook)) + # Each model request of a turn, for the card's sealed detail (card_detail.py). Older Hermes has no such hook. + try: + from hermes_cli.plugins import VALID_HOOKS as _hooks + if "post_api_request" in _hooks: + ctx.register_hook("post_api_request", partial(observe_managed, "post_api_request")) + except ImportError: + pass # Registration is additive: retain the explicitly selected legacy # transport. Older SDKs can warn-and-register unknown names, so # registration alone is not proof of an emitter. diff --git a/tests/test_card_detail.py b/tests/test_card_detail.py new file mode 100644 index 0000000..9028faa --- /dev/null +++ b/tests/test_card_detail.py @@ -0,0 +1,142 @@ +from __future__ import annotations + +import json +import sqlite3 +import unittest +from pathlib import Path + +from loopdy_plugin import card_detail +from loopdy_plugin.managed_notifications import ManagedNotificationError +from loopdy_plugin.notification_crypto import b64url_decode, b64url_encode +from test_managed_notifications import ManagedNotificationTests + +VECTOR = Path(__file__).resolve().parents[1] / "fixtures" / "contracts" / "sealed-card-v1-vector.json" +KEY = bytes(range(32)) + + +class CardDetailFormatTests(unittest.TestCase): + def test_shared_vector_opens_and_is_what_this_host_seals(self): + vector = json.loads(VECTOR.read_text()) + key = b64url_decode(vector["key"]) + self.assertEqual(card_detail.open_sealed(key, vector["timestamp"], vector["sealed"]), vector["detail"]) + plain = json.dumps(vector["detail"], ensure_ascii=False, separators=(",", ":"), sort_keys=True).encode() + self.assertEqual(card_detail.seal(key, vector["timestamp"], plain, nonce=b64url_decode(vector["nonce"])), + vector["sealed"]) + with self.assertRaises(Exception): # another update's time + card_detail.open_sealed(key, vector["timestamp"] + 1, vector["sealed"]) + + def test_detail_stays_inside_one_rows_share_and_keeps_secrets_out(self): + detail = card_detail.new_detail(100) + card_detail.tool_started(detail, "terminal", {"command": "export OPENAI_API_KEY=sk-" + "a" * 48}) + self.assertEqual(detail["note"], "") + for index in range(5): + card_detail.tool_started(detail, "web_search", {"query": "protein powder price per lb " + "x" * 300}) + card_detail.tool_finished(detail, "web_search", {}) + detail["preview"], detail["say"] = "p" * 5_000, "s" * 5_000 + detail["goals"] = {"a": "g" * 60, "b": "h" * 60, "c": "i" * 60} + plain = card_detail.plaintext(detail, "completed") + self.assertLessEqual(len(card_detail.seal(KEY, 1, plain)), card_detail.MAX_SEALED_CHARS) + body = json.loads(plain) + self.assertEqual(body["tr"][0]["c"], 5) + self.assertEqual(body["s"], 6) + self.assertNotIn("t", body) # nothing is in progress once the turn ended + + +class SealedCardUpdateTests(ManagedNotificationTests): + def bind(self, key: bytes | None = KEY): + self.service.observe("pre_llm_call", profile="default", session_id="native-session", turn_id="turn-a", platform="desktop") + with sqlite3.connect(self.service.db_path) as db: + db.execute("INSERT INTO activities(activity_id,grant_id,profile,session_id,session_ref,lease_expires,work_turn,state) VALUES(?,?,?,?,?,?,?,'active')", + ("activity-a", self.grant_id, "default", "native-session", "x" * 43, self.now + 600, "turn-a")) + if key: self.service.set_card_key(self.grant_id, "activity-a", b64url_encode(key)) + + def pending(self) -> dict: + with sqlite3.connect(self.service.db_path) as db: + return json.loads(db.execute("SELECT raw FROM pending WHERE activity_id='activity-a' AND state='pending'").fetchone()[0]) + + def detail(self, update: dict) -> dict: + return card_detail.open_sealed(KEY, update["timestamp"], update["sealed"]) + + def tool(self, hook: str, name: str, **args): + self.service.observe(hook, profile="default", session_id="native-session", turn_id="turn-a", tool_name=name, + args=args, tool_call_id="call-1") + + def test_without_a_key_updates_are_what_they_were(self): + self.bind(key=None) + self.tool("pre_tool_call", "web_search", query="private query") + update = self.pending() + self.assertNotIn("sealed", update); self.assertNotIn("quiet", update) + self.assertNotIn("private", json.dumps(update)) + + def test_a_key_makes_the_next_update_carry_the_step_only_inside_the_seal(self): + self.bind() + first = self.pending() # setting the key queues the card's state at once + self.assertEqual(self.detail(first)["s"], 0) + self.now += 10 + self.tool("pre_tool_call", "web_search", query="protein price per lb") + update = self.pending() + self.assertNotIn("protein", json.dumps(update)) + self.assertIsNone(update["latestTool"]) + detail = self.detail(update) + self.assertEqual((detail["t"], detail["n"], detail["s"], detail["b"]), ("web_search", "protein price per lb", 1, self.now - 10)) + self.assertNotIn("quiet", update) # the phase changed: high priority + + def test_a_new_step_alone_goes_quietly_and_one_update_in_thirty_seconds_is_loud(self): + self.bind() + self.tool("pre_tool_call", "web_search", query="one") + self.service.drain_pending() + self.now += 9 + self.tool("post_tool_call", "web_search") + self.tool("pre_tool_call", "read_file", path="/Users/someone/prices.csv") + update = self.pending() + self.assertIs(update["quiet"], True) + detail = self.detail(update) + self.assertEqual(detail["n"], "prices.csv") + self.assertEqual(detail["tr"], [{"t": "web_search", "c": 1, "n": "one"}]) + self.service.drain_pending() + self.now += 31 + self.tool("post_tool_call", "read_file") + self.assertNotIn("quiet", self.pending()) + + def test_a_question_waits_on_the_card_and_the_reply_shows_at_the_end(self): + self.bind() + self.tool("pre_tool_call", "clarify", question="Send the order for $47.00?") + update = self.pending() + self.assertEqual(update["phase"], "waiting") + self.assertEqual(self.detail(update)["q"], "Send the order for $47.00?") + self.tool("post_tool_call", "clarify") + self.assertEqual(self.pending()["phase"], "using_tool") + self.service.observe("post_api_request", profile="default", session_id="native-session", turn_id="turn-a", + assistant_message={"content": "Comparing four brands now."}, model="vendor/sample-model-1", + usage={"prompt_tokens": 30_300}, context_length=272_000) + self.now += 9 + self.tool("pre_tool_call", "execute_code") + detail = self.detail(self.pending()) + self.assertEqual((detail["say"], detail["cu"], detail["cm"], detail["m"]), + ("Comparing four brands now.", 30_300, 272_000, "sample-model-1")) + self.service.observe("post_llm_call", profile="default", session_id="native-session", turn_id="turn-a", + assistant_response="Cheapest per lb is Northfield Whey at $9.40.") + self.service.observe("on_session_end", profile="default", session_id="native-session", turn_id="turn-a", + completed=True, platform="desktop") + update = self.pending() + self.assertEqual(update["phase"], "completed") + self.assertEqual(self.detail(update)["p"], "Cheapest per lb is Northfield Whey at $9.40.") + + def test_a_service_that_refuses_sealed_detail_gets_plain_updates_after(self): + self.bind() + original = self.service.transport + def transport(method, path, raw, headers): + if path.endswith("/updates") and b'"sealed"' in raw: raise ManagedNotificationError("notification_activity_invalid", 400) + return original(method, path, raw, headers) + self.service.transport = transport + self.service.drain_pending() + self.now += 31 + self.tool("pre_tool_call", "web_search", query="one") + self.assertNotIn("sealed", self.pending()) + + def test_only_a_real_key_for_a_known_card_is_taken(self): + self.bind(key=None) + for bad in ("short", "!" * 43, None): + with self.assertRaises(ManagedNotificationError): self.service.set_card_key(self.grant_id, "activity-a", bad) + with self.assertRaises(ManagedNotificationError): self.service.set_card_key(self.grant_id, "activity-b", b64url_encode(KEY)) + self.assertEqual(self.service.capabilities()["sealedCardDetail"], {"version": 1}) From 1b51a2560f17a16841dd4ac37950237abd144c23 Mon Sep 17 00:00:00 2001 From: GordieBox Date: Wed, 11 Nov 2026 18:36:31 -0600 Subject: [PATCH 2/2] A waiting question stays on the card, and review fixes A turn's state is sent again once a minute while no hook fires, so a question that waits or a long tool call does not go stale. An update that takes the place of a high-priority one keeps its priority. The same key again changes nothing. A malformed URL or a long tool name never stops a card's updates. Co-Authored-By: Claude Fable 5.2 --- docs/NOTIFICATIONS.md | 4 ++ loopdy_plugin/card_detail.py | 8 +++- loopdy_plugin/managed_notifications.py | 46 ++++++++++++++++-- tests/test_card_detail.py | 66 +++++++++++++++++++++++++- 4 files changed, 117 insertions(+), 7 deletions(-) diff --git a/docs/NOTIFICATIONS.md b/docs/NOTIFICATIONS.md index d77c00a..b6a7bd5 100644 --- a/docs/NOTIFICATIONS.md +++ b/docs/NOTIFICATIONS.md @@ -397,6 +397,10 @@ drops that card's key and sends plain updates. While the agent asks a question with `clarify`, or a command waits for approval, the card's phase is `waiting`. +A card goes stale on the phone 120 seconds after its last update. While a turn runs and no hook fires (a question +that waits, one long tool call), each Hermes process sends that turn's state again once a minute. It stops 30 +minutes after the turn's last hook, unless the turn waits for the person. + ## Host storage The host's notification key and its grants, subscriptions, content keys and pending events live under diff --git a/loopdy_plugin/card_detail.py b/loopdy_plugin/card_detail.py index c5629f8..247b5fe 100644 --- a/loopdy_plugin/card_detail.py +++ b/loopdy_plugin/card_detail.py @@ -65,7 +65,10 @@ def _line(value: Any, limit: int) -> str: def _site(value: Any) -> str: if isinstance(value, list): value = value[0] if value else "" if not isinstance(value, str): return "" - host = urlsplit(value if "//" in value else "//" + value).hostname or "" + try: + host = urlsplit(value if "//" in value else "//" + value).hostname or "" + except ValueError: + return "" return _line(host.removeprefix("www."), 60) @@ -149,6 +152,9 @@ def encoded() -> bytes: for key in ("p", "q"): while len(encoded()) > _MAX_PLAINTEXT_BYTES and len(body.get(key, "")) > 40: body[key] = body[key][:len(body[key]) // 2].rstrip() + "…" + if len(encoded()) > _MAX_PLAINTEXT_BYTES: + # Tool names or what is left in a script that takes many bytes a character: the timer and count alone. + body = {"v": VERSION, "b": detail["started"], "s": detail["steps"]} return encoded() diff --git a/loopdy_plugin/managed_notifications.py b/loopdy_plugin/managed_notifications.py index fc2f380..5a20896 100644 --- a/loopdy_plugin/managed_notifications.py +++ b/loopdy_plugin/managed_notifications.py @@ -92,6 +92,9 @@ # Seconds between a card's updates while it carries sealed detail, and between its high-priority ones. _DETAIL_SPACING = 8 _LOUD_SPACING = 30 +# How often each process looks for running turns to send again, and how long after a turn's last hook it still does. +_CARD_REFRESH_TICK = 15 +_REFRESH_WITHOUT_HOOKS = 1800 # A rotating sign-in (the Nous Portal's lasts a day) runs out if bighelp stays closed. # Waking the phone this often gives it more than one chance to renew before then. _SIGN_IN_WAKE_SECONDS = 8 * 3600 @@ -366,6 +369,7 @@ def __init__(self, directory: Path, *, transport: Callable = _https_request, self._lock = state["lock"] self._wake, self._stop = state["wake"], threading.Event() self._worker: threading.Thread | None = None + self._keeper: threading.Thread | None = None self._worker_lock = None self._loaded_profiles: set[str] = state["loaded_profiles"] self._approval_profiles: set[str] = state["approval_profiles"] @@ -417,9 +421,10 @@ def __init__(self, directory: Path, *, transport: Callable = _https_request, """) # Added for sealed card detail: the chat row's key from the phone, and when an # update last went out at high priority. - columns = {row[1] for row in db.execute("PRAGMA table_info(activities)")} - if "card_key" not in columns: db.execute("ALTER TABLE activities ADD COLUMN card_key BLOB") - if "last_loud_at" not in columns: db.execute("ALTER TABLE activities ADD COLUMN last_loud_at INTEGER NOT NULL DEFAULT 0") + # The dashboard and the gateway can start together: the one that comes second finds the column there. + for column in ("card_key BLOB", "last_loud_at INTEGER NOT NULL DEFAULT 0"): + try: db.execute("ALTER TABLE activities ADD COLUMN " + column) + except sqlite3.OperationalError: pass db.executescript(live_alerts.SCHEMA) db.executescript(scheduled_links.SCHEMA) @@ -906,8 +911,11 @@ def set_card_key(self, grant_id: str, activity_id: str, key: Any): if secret is None: raise ManagedNotificationError("notification_card_key_invalid", 400) with self._lock: with self._db() as db: - row = db.execute("SELECT profile,session_id,work_turn FROM activities WHERE activity_id=? AND grant_id=?", (activity_id, grant_id)).fetchone() + row = db.execute("SELECT profile,session_id,work_turn,card_key FROM activities WHERE activity_id=? AND grant_id=?", (activity_id, grant_id)).fetchone() if not row: raise ManagedNotificationError("notification_activity_unknown", 404) + if row["card_key"] is not None and bytes(row["card_key"]) == secret: + # The app sends the key again with each registration it repeats. Nothing changed. + return {"version": 1, "activityId": activity_id, "grantId": grant_id, "state": "sealed"} db.execute("UPDATE activities SET card_key=?,last_signature=NULL WHERE activity_id=?", (secret, activity_id)) work = self._work.get((row["profile"], row["session_id"], row["work_turn"])) if row["work_turn"] else None if work is not None and not work["terminal"]: @@ -1637,6 +1645,7 @@ def _observe_card_approval(self, hook: str, profile: str, payload: dict[str, Any with self._lock: work = self._work.get((profile, session_id, turn)) if work is None or work["terminal"] or work["outcome"] is not None: return + work.setdefault("detail", card_detail.new_detail(work["observed_at"])) asking = hook == "pre_approval_request" work["detail"]["question"] = self._rich_text(payload.get("description") or payload.get("command")) if asking else "" work["phase"] = "waiting" if asking else "using_tool" @@ -1677,8 +1686,10 @@ def _queue_activity(self, profile: str, session_id: str, turn: str, phase: str, update["sealed"] = card_detail.seal(key, timestamp, plain) # Apple limits high-priority card updates. A new step alone goes at low priority, # except that one update every _LOUD_SPACING is high, so a locked phone keeps up. + # An update that takes the place of a high-priority one that never left is high too. same_status = (row["last_signature"] or "").startswith(status[:-1] + ",") - loud = urgent or not same_status or due - row["last_loud_at"] >= _LOUD_SPACING + waiting_loud = pending is not None and not json.loads(bytes(pending["raw"])).get("quiet") + loud = urgent or waiting_loud or not same_status or due - row["last_loud_at"] >= _LOUD_SPACING if not loud: update["quiet"] = True # Only nonterminal updates may be superseded; terminal is durable. db.execute("DELETE FROM pending WHERE activity_id=? AND state='pending'", (row["activity_id"],)) @@ -1696,6 +1707,10 @@ def producer_loaded(self, profile: str, *, start_worker: bool = True, self._approval_profiles.add(profile) if clarification_producer_loaded: self._clarification_profiles.add(profile) + if start_worker and self._keeper is None: + # In every Hermes process, not only the one that sends: a turn's state lives where it runs. + self._keeper = threading.Thread(target=self._keep_cards_current, name="loopdy-card-refresh", daemon=True) + self._keeper.start() if start_worker and self._worker is None: lock_path = self.directory / "worker.lock" fd = os.open(lock_path, os.O_CREAT | os.O_RDWR | os.O_NOFOLLOW, 0o600) @@ -1707,6 +1722,27 @@ def producer_loaded(self, profile: str, *, start_worker: bool = True, self._worker = threading.Thread(target=self._run, name="loopdy-managed-notifications", daemon=True) self._worker.start() + def _keep_cards_current(self): + while not self._stop.wait(_CARD_REFRESH_TICK): + try: self.refresh_activities() + except (ValueError, OSError, sqlite3.Error): logger.warning("Live Activity refresh unavailable") + + def refresh_activities(self): + """Sends a running turn's state again while no hook fires. + + A card goes stale 120 seconds after its last update. A question that waits for the person, + or one long tool call, fires no hook in that time, and the card then said its updates paused. + `_queue_activity` sends an unchanged state at most once in _ACTIVITY_REFRESH_SECONDS. A turn with + no hook for _REFRESH_WITHOUT_HOOKS is left alone, unless it waits for the person. + """ + now = int(self.clock()) + with self._lock: + for (profile, session_id, turn), work in list(self._work.items()): + if work["terminal"] or work["outcome"] is not None: continue + if work["phase"] != "waiting" and now - work["observed_at"] > _REFRESH_WITHOUT_HOOKS: continue + phase, count, terminal = self._work_projection(work) + self._queue_activity(profile, session_id, turn, phase, count, terminal, detail=work.get("detail")) + def close(self): self._stop.set(); self._wake.set() if self._worker is not None: self._worker.join(timeout=15) diff --git a/tests/test_card_detail.py b/tests/test_card_detail.py index 9028faa..5620ffc 100644 --- a/tests/test_card_detail.py +++ b/tests/test_card_detail.py @@ -47,7 +47,13 @@ def bind(self, key: bytes | None = KEY): self.service.observe("pre_llm_call", profile="default", session_id="native-session", turn_id="turn-a", platform="desktop") with sqlite3.connect(self.service.db_path) as db: db.execute("INSERT INTO activities(activity_id,grant_id,profile,session_id,session_ref,lease_expires,work_turn,state) VALUES(?,?,?,?,?,?,?,'active')", - ("activity-a", self.grant_id, "default", "native-session", "x" * 43, self.now + 600, "turn-a")) + ("activity-a", self.grant_id, "default", "native-session", "x" * 43, self.now + 7_200, "turn-a")) + original = self.service.transport + def transport(method, path, raw, headers): + # The notification service takes an update. + if path.endswith("/updates"): return {"version": 1, "status": "accepted", "deliveryId": "live_fixture"} + return original(method, path, raw, headers) + self.service.transport = transport if key: self.service.set_card_key(self.grant_id, "activity-a", b64url_encode(key)) def pending(self) -> dict: @@ -140,3 +146,61 @@ def test_only_a_real_key_for_a_known_card_is_taken(self): with self.assertRaises(ManagedNotificationError): self.service.set_card_key(self.grant_id, "activity-a", bad) with self.assertRaises(ManagedNotificationError): self.service.set_card_key(self.grant_id, "activity-b", b64url_encode(KEY)) self.assertEqual(self.service.capabilities()["sealedCardDetail"], {"version": 1}) + + +class CardRefreshTests(SealedCardUpdateTests): + def test_a_question_that_waits_is_sent_again_before_the_card_goes_stale(self): + self.bind() + self.tool("pre_tool_call", "clarify", question="Send the order for $47.00?") + first = self.pending() + self.service.drain_pending() + self.now += 30 + self.service.refresh_activities() # inside the minute: nothing new + with sqlite3.connect(self.service.db_path) as db: + self.assertEqual(db.execute("SELECT COUNT(*) FROM pending WHERE activity_id='activity-a' AND state='pending'").fetchone()[0], 0) + self.now += 2_000 # no hook for half an hour and more: a question still waits + self.service.refresh_activities() + again = self.pending() + self.assertEqual(again["phase"], "waiting") + self.assertGreater(again["timestamp"], first["timestamp"]) + self.assertEqual(self.detail(again)["q"], "Send the order for $47.00?") + self.assertNotIn("quiet", again) + + def test_a_long_tool_call_is_sent_again_but_not_for_ever(self): + self.bind() + self.tool("pre_tool_call", "terminal", command="make build") + self.service.drain_pending() + self.now += 90 + self.service.refresh_activities() + self.assertEqual(self.detail(self.pending())["t"], "terminal") + self.service.drain_pending() + self.now += 1_900 + self.service.refresh_activities() + with sqlite3.connect(self.service.db_path) as db: + self.assertEqual(db.execute("SELECT COUNT(*) FROM pending WHERE activity_id='activity-a' AND state='pending'").fetchone()[0], 0) + + def test_a_phase_change_that_never_left_keeps_its_priority_when_a_step_takes_its_place(self): + self.bind() + self.service.drain_pending() + self.now += 2 + self.tool("pre_tool_call", "web_search", query="one") # thinking -> using_tool, waits for its turn + self.assertNotIn("quiet", self.pending()) + self.tool("post_tool_call", "web_search") + self.tool("pre_tool_call", "read_file", path="a.txt") # same phase, takes its place + self.assertNotIn("quiet", self.pending()) + + def test_the_same_key_again_changes_nothing_and_odd_input_never_stops_updates(self): + self.bind() + self.service.drain_pending() + self.service.set_card_key(self.grant_id, "activity-a", b64url_encode(KEY)) + with sqlite3.connect(self.service.db_path) as db: + self.assertEqual(db.execute("SELECT COUNT(*) FROM pending WHERE activity_id='activity-a' AND state='pending'").fetchone()[0], 0) + self.now += 10 + self.tool("pre_tool_call", "web_extract", url="http://[broken") + self.assertEqual(self.pending()["phase"], "using_tool") + detail = card_detail.new_detail(1) + for index in range(3): + card_detail.tool_started(detail, "工" * 48 + str(index), {}) + card_detail.tool_finished(detail, "工" * 48 + str(index), {}) + detail["tool"] = "具" * 48 + self.assertLessEqual(len(card_detail.seal(KEY, 1, card_detail.plaintext(detail, "using_tool"))), card_detail.MAX_SEALED_CHARS)