diff --git a/docs/NOTIFICATIONS.md b/docs/NOTIFICATIONS.md index b6a7bd5..58a8f20 100644 --- a/docs/NOTIFICATIONS.md +++ b/docs/NOTIFICATIONS.md @@ -374,6 +374,13 @@ grant (`PUT/DELETE /notifications/enrollments//live-activities//work`). The app asks the moment the turn starts. Hermes fires +the turn's first hook (`pre_llm_call`) a little later, once the turn's memory and context are ready, and only +then does the host know the turn. So the route holds its answer up to 8 seconds (`WORK_WAIT_SECONDS`) for +running work to show in that chat. An app that was told "no work" kept the card to itself for the whole turn: +the card then got no update with the app away, and no sealed detail. + ### Sealed card detail An app that shows more on the card gives the host a key for that chat's row diff --git a/loopdy_plugin/managed_notifications.py b/loopdy_plugin/managed_notifications.py index 5a20896..f2756f4 100644 --- a/loopdy_plugin/managed_notifications.py +++ b/loopdy_plugin/managed_notifications.py @@ -95,6 +95,9 @@ # 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 +# The longest the work route holds its answer for a turn that is starting, and how often it looks. +WORK_WAIT_SECONDS = 8.0 +_WORK_WAIT_TICK = 0.1 # 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 @@ -806,28 +809,39 @@ def subscribe(self, grant_id: str, profile: str, session_id: str, enabled: bool) db.execute("DELETE FROM activities WHERE grant_id=? AND session_ref=?", (grant_id, reference)) return {"version": 1, "grantId": grant_id, "profile": profile, "sessionId": session_id, "sessionReference": reference, "enabled": enabled} - def work_snapshot(self, grant_id: str, profile: str, session_id: str): + def work_snapshot(self, grant_id: str, profile: str, session_id: str, *, wait: float = 0.0): """Read only this process's public-hook observations, never DB starts. A current session observation is not correlation with a mobile frame. Retained older turns remain addressable by explicit activity registration. + + The app asks the moment a turn starts. Hermes fires the turn's first hook a little later, + once the turn's memory and context are ready, so until then this chat has no work or only + its last, finished turn. `wait` holds the answer up to that many seconds for running work + to show. An app told "no work" kept the card to itself for the whole turn: it then got no + update with the app away, and no sealed detail. """ grant = self.enrollment(grant_id)["grant"] if profile != grant["profile"]: raise ManagedNotificationError("notification_scope_forbidden", 403) self._session(profile, session_id) - with self._lock, self._db() as db: - self._require_subscription(db, grant_id, profile, session_id) - work = next((value for key, value in reversed(self._work.items()) - if key[:2] == (profile, session_id)), None) - snapshot = None - if work is not None: - phase, count, terminal = self._work_projection(work) - snapshot = {"profile": profile, "sessionId": session_id, - "turnId": work["turn"], "phase": phase, - "activeSubagentCount": count, "terminal": terminal, - "outcome": work["outcome"], "observedAt": work["observed_at"]} - return {"version": 1, "grantId": grant_id, "work": snapshot} + deadline = time.monotonic() + max(0.0, min(float(wait), WORK_WAIT_SECONDS)) + while True: + with self._lock, self._db() as db: + self._require_subscription(db, grant_id, profile, session_id) + work = next((value for key, value in reversed(self._work.items()) + if key[:2] == (profile, session_id)), None) + snapshot = None + if work is not None: + phase, count, terminal = self._work_projection(work) + snapshot = {"profile": profile, "sessionId": session_id, + "turnId": work["turn"], "phase": phase, + "activeSubagentCount": count, "terminal": terminal, + "outcome": work["outcome"], "observedAt": work["observed_at"]} + if (snapshot is not None and not snapshot["terminal"]) or time.monotonic() >= deadline: + return {"version": 1, "grantId": grant_id, "work": snapshot} + # Outside the lock, so the turn's hooks run. This copy's close ends the wait. + if self._stop.wait(_WORK_WAIT_TICK): deadline = 0.0 def _require_subscription(self, db, grant_id: str, profile: str, session_id: str): # Recheck local authority after cloud/SessionDB awaits, in the transaction diff --git a/loopdy_plugin/managed_notifications_api.py b/loopdy_plugin/managed_notifications_api.py index 6992621..8d30783 100644 --- a/loopdy_plugin/managed_notifications_api.py +++ b/loopdy_plugin/managed_notifications_api.py @@ -7,7 +7,7 @@ from pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictInt from . import host_telemetry -from .managed_notifications import ManagedNotificationError, get_managed_notifications +from .managed_notifications import WORK_WAIT_SECONDS, ManagedNotificationError, get_managed_notifications logger = logging.getLogger("hermes.plugins.bighelp.notifications") router = APIRouter(prefix="/notifications") @@ -166,7 +166,9 @@ def channels(grant_id: str): @router.post("/enrollments/{grant_id}/work") def work_snapshot(grant_id: str, body: WorkBody): - return _call(lambda: get_managed_notifications().work_snapshot(grant_id, body.profile, body.sessionId)) + # The app asks as a turn starts, before Hermes fires the turn's first hook: wait for it. + return _call(lambda: get_managed_notifications().work_snapshot( + grant_id, body.profile, body.sessionId, wait=WORK_WAIT_SECONDS)) @router.get("/enrollments/{grant_id}/events/{event_id}") diff --git a/tests/test_managed_notifications.py b/tests/test_managed_notifications.py index 4602712..e6fb0da 100644 --- a/tests/test_managed_notifications.py +++ b/tests/test_managed_notifications.py @@ -5,6 +5,8 @@ from pathlib import Path import sqlite3 import tempfile +import threading +import time import unittest import uuid import hashlib @@ -221,6 +223,27 @@ def test_current_work_snapshot_is_scoped_and_canonical(self): with self.assertRaises(ManagedNotificationError): self.service.work_snapshot(self.grant_id,"other","native-session") + def test_work_snapshot_waits_for_a_turn_that_is_starting(self): + # The app asks the moment a turn starts. Hermes fires the turn's first hook a little later. + self.service.observe("pre_llm_call", profile="default", session_id="native-session", turn_id="earlier") + self.service.observe("on_session_end", profile="default", session_id="native-session", turn_id="earlier", completed=True) + self.assertTrue(self.service.work_snapshot(self.grant_id, "default", "native-session")["work"]["terminal"]) + starting = threading.Timer(0.3, lambda: self.service.observe( + "pre_llm_call", profile="default", session_id="native-session", turn_id="starting")) + starting.start() + try: + work = self.service.work_snapshot(self.grant_id, "default", "native-session", wait=5)["work"] + finally: + starting.join() + self.assertEqual((work["turnId"], work["terminal"]), ("starting", False)) + # Running work is answered at once, and a chat where no turn starts gets its answer when the wait ends. + began = time.monotonic() + self.assertEqual(self.service.work_snapshot(self.grant_id, "default", "native-session", wait=5)["work"]["turnId"], "starting") + self.assertLess(time.monotonic() - began, 1) + began = time.monotonic() + self.assertIsNone(self.service.work_snapshot(self.grant_id, "default", "quiet-session", wait=0.3)["work"]) + self.assertGreaterEqual(time.monotonic() - began, 0.3) + def test_one_native_terminal_event_persists_and_retries_identical_rich_payload(self): payload=dict(profile="default",session_id="native-session",turn_id="turn-a",completed=True,platform="desktop") self.service.observe("post_llm_call",profile="default",session_id="native-session",turn_id="turn-a",assistant_response="The requested fixture work is complete.")