diff --git a/plugin/pheby/adapter.py b/plugin/pheby/adapter.py index bb6ddcc..1b2936b 100644 --- a/plugin/pheby/adapter.py +++ b/plugin/pheby/adapter.py @@ -137,6 +137,18 @@ class PhebyAdapter(BasePlatformAdapter): conversation_id = self._conv_from_chat_id(chat_id) metadata = metadata or {} + # Scheduled sends do not belong to any active assistant draft. Save + # before broadcasting: a notification/WS event alone is not history. + if metadata.get("job_id"): + try: + event = await hermes_bridge.persist_cron_delivery( + conversation_id, content, metadata) + except Exception: + logger.exception("[pheby] cron delivery persistence failed") + return SendResult(success=False, error="Unable to save cron delivery") + await self._server.broadcast(event) + return SendResult(success=True, message_id=event["message_id"]) + # Commentary and gateway notices are complete standalone timeline # items. They must not close the primary assistant draft/run. if metadata.get("_interim_send") or metadata.get("non_conversational"): diff --git a/plugin/pheby/hermes_bridge.py b/plugin/pheby/hermes_bridge.py index 26388ed..c319777 100644 --- a/plugin/pheby/hermes_bridge.py +++ b/plugin/pheby/hermes_bridge.py @@ -200,6 +200,38 @@ async def list_conversations(server: Any = None) -> List[Dict[str, Any]]: "source": "pheby", }) + # 3. Scheduled deliveries have no model-session activity timestamp. Merge + # their durable recency so empty Home chats retain unread state and sort + # correctly even after reopening or losing the rebuildable router index. + db = _session_db() + if db is not None: + try: + deliveries = await asyncio.to_thread( + db._read_all, + "SELECT s.chat_id, s.id, MAX(m.timestamp) AS last_active " + "FROM sessions s JOIN messages m ON m.session_id = s.id " + "WHERE s.source = ? GROUP BY s.id, s.chat_id", + ("pheby_delivery",), + ) + by_id = {item["conversation_id"]: item for item in out} + for row in deliveries: + cid = str(row["chat_id"] or "") + if not cid: + continue + last_active = _iso(row["last_active"]) + item = by_id.get(cid) + if item is None: + item = {"conversation_id": cid, + "name": router_names.get(cid) or "Scheduled messages", + "session_id": str(row["id"]), + "last_active": last_active, "source": "pheby"} + out.append(item) + by_id[cid] = item + elif last_active and last_active > (item.get("last_active") or ""): + item["last_active"] = last_active + except Exception: + logger.warning("[pheby] delivery recency load failed", exc_info=True) + out.sort(key=lambda c: (c.get("last_active") is None, c.get("last_active") or ""), reverse=False) out.sort(key=lambda c: c.get("last_active") or "", reverse=True) @@ -235,6 +267,44 @@ def _display_user_text(text: str) -> str: return body.split(end, 1)[0] if end in body else text +async def persist_cron_delivery(conversation_id: str, content: str, + metadata: Dict[str, Any]) -> Dict[str, Any]: + """Save display-only delivery history without mutating a live model turn. + + Cron runs have their own sessions; Hermes does not mirror their output + into the destination transcript by default. Keep a separate source-tagged + session in the existing DB so display history shares real row-ID cursors, + but the gateway never loads these assistant rows as active model context. + Reuse the runner's DB; never open the production state DB from the plugin. + """ + db = _session_db() + if db is None: + raise RuntimeError("Conversation database unavailable for cron delivery") + key = _session_key_for(conversation_id) + sid = f"pheby-delivery-{uuid.uuid5(uuid.NAMESPACE_URL, key).hex}" + timestamp = time.time() + + def _persist() -> int: + db.create_session(sid, "pheby_delivery", session_key=key, + chat_id=conversation_id, chat_type="dm") + return db.append_message( + sid, "assistant", content, timestamp=timestamp, + display_kind="cron_delivery", + display_metadata={"job_id": str(metadata["job_id"])}) + + row_id = await asyncio.to_thread(_persist) + server = _current_server() + if server is not None: + await server.router.ensure_conversation(conversation_id) + return { + "type": proto.S_MESSAGE_COMPLETE, + "conversation_id": conversation_id, + "message_id": f"m{row_id}", + "text": content, + "ts": _iso(timestamp), + } + + async def conversation_history(conversation_id: str, limit: int, before_id: Optional[int] = None ) -> Tuple[List[Dict[str, Any]], bool, bool]: @@ -269,8 +339,8 @@ async def conversation_history(conversation_id: str, limit: int, # absent. Hermes's own decoder handles archived/compacted rows. ids = await asyncio.to_thread( db._read_all, - "SELECT id FROM sessions WHERE session_key = ? AND source = ? ORDER BY started_at, id", - (session_key, "pheby"), + "SELECT id FROM sessions WHERE session_key = ? AND source IN (?, ?) ORDER BY started_at, id", + (session_key, "pheby", "pheby_delivery"), ) session_ids = [str(row["id"]) for row in ids] if session_id and session_id not in session_ids: @@ -385,8 +455,8 @@ async def delete_conversation(conversation_id: str) -> bool: try: rows = await asyncio.to_thread( db._read_all, - "SELECT id FROM sessions WHERE session_key = ? AND source = ? ORDER BY started_at, id", - (session_key, "pheby"), + "SELECT id FROM sessions WHERE session_key = ? AND source IN (?, ?) ORDER BY started_at, id", + (session_key, "pheby", "pheby_delivery"), ) ids = [str(row["id"]) for row in rows] if session_id and session_id not in ids: diff --git a/tests/test_cron_delivery.py b/tests/test_cron_delivery.py new file mode 100644 index 0000000..1ec113d --- /dev/null +++ b/tests/test_cron_delivery.py @@ -0,0 +1,109 @@ +"""Cron transport success must mean the message survives a chat reopen.""" +import pytest + +from gateway.config import PlatformConfig +from hermes_state import SessionDB +from pheby import hermes_bridge as hb, protocol as proto +from pheby.adapter import PhebyAdapter +from pheby.server import PhebyServer + + +@pytest.fixture +def delivery_stack(tmp_path, monkeypatch): + db = SessionDB(tmp_path / "state.db") + monkeypatch.setattr(hb, "_session_db", lambda: db) + monkeypatch.setattr(hb, "_session_store", lambda: None) + adapter = PhebyAdapter(PlatformConfig(enabled=True, extra={"secret": "test-secret"})) + server = PhebyServer(adapter._pcfg, adapter=adapter) + adapter._server = server + hb.set_adapter(adapter) + hb.set_server(server) + yield adapter, server, db + hb.clear_services(adapter) + hb.set_server(None) + hb._ACTIVE_RUNS.clear() + db.close() + + +@pytest.mark.asyncio +async def test_cron_delivery_survives_reopen_without_touching_active_turn(delivery_stack): + adapter, server, db = delivery_stack + cid = "home" + key = hb._session_key_for(cid) + db.create_session("active-session", "pheby", session_key=key) + db.append_message("active-session", "user", "My ongoing question") + adapter._drafts[cid] = {"message_id": "draft-active", "text": "Still thinking"} + hb._ACTIVE_RUNS[cid] = {"run_id": "active-run", "started": 0} + + # No WebSocket clients connected: receiving a push is not durable delivery. + result = await adapter.send(cid, "Inbox filed successfully", metadata={"job_id": "daily-inbox", "notify": True}) + assert result.success + history, found, has_more = await hb.conversation_history(cid, 20) + assert [m["text"] for m in history] == ["My ongoing question", "Inbox filed successfully"] + assert history[-1]["message_id"] == result.message_id + assert found and not has_more + assert hb.active_run_id(cid) == "active-run" + assert adapter._drafts[cid]["message_id"] == "draft-active" + assert [m["content"] for m in db.get_messages_as_conversation("active-session")] == ["My ongoing question"] + assert await server.router.get_name(cid) is not None + conversations = await hb.list_conversations(server) + assert conversations[0]["conversation_id"] == cid + assert conversations[0]["last_active"] == history[-1]["ts"] + + # Paging uses real global message row IDs across chat and delivery history. + previous, _, _ = await hb.conversation_history(cid, 20, before_id=int(result.message_id[1:])) + assert [m["text"] for m in previous] == ["My ongoing question"] + + +@pytest.mark.asyncio +async def test_cron_delivery_does_not_claim_success_when_save_fails(delivery_stack, monkeypatch): + adapter, server, db = delivery_stack + broadcasts = [] + + async def broadcast(event): + broadcasts.append(event) + + def fail(*args, **kwargs): + raise OSError("disk unavailable") + + monkeypatch.setattr(server, "broadcast", broadcast) + monkeypatch.setattr(db, "append_message", fail) + result = await adapter.send("home", "A report", metadata={"job_id": "daily"}) + assert not result.success + assert broadcasts == [] + + +@pytest.mark.asyncio +async def test_cron_delivery_is_readable_over_ws_after_reconnect(delivery_stack): + import aiohttp + + adapter, server, db = delivery_stack + server.config.port = 0 + assert await server.start() + try: + port = server._site._server.sockets[0].getsockname()[1] + async with aiohttp.ClientSession() as http: + async def connect(): + ws = await http.ws_connect(f"http://127.0.0.1:{port}/ws") + await ws.send_json({"type": "hello", "secret": "test-secret", "protocol_version": proto.PROTOCOL_VERSION}) + assert (await ws.receive_json(timeout=5))["type"] == proto.S_READY + return ws + + ws = await connect() + result = await adapter.send("home", "Persistent scheduled report", metadata={"job_id": "daily"}) + live = await ws.receive_json(timeout=5) + assert live["message_id"] == result.message_id + await ws.close() + ws = await connect() + await ws.send_json({"type": "conversation.open", "conversation_id": "home", "request_id": "reopen"}) + history = await ws.receive_json(timeout=5) + assert history["type"] == proto.S_CONVERSATION_HISTORY + assert history["messages"] == [{"message_id": result.message_id, "role": "assistant", "text": live["text"], "ts": live["ts"]}] + await ws.close() + + # Another chat cannot see this delivery, and deletion clears its archive. + assert (await hb.conversation_history("other-chat", 20))[0] == [] + assert await hb.delete_conversation("home") + assert (await hb.conversation_history("home", 20))[0] == [] + finally: + await server.stop() diff --git a/tests/test_pheby.py b/tests/test_pheby.py index 28b44cb..98c025a 100644 --- a/tests/test_pheby.py +++ b/tests/test_pheby.py @@ -913,7 +913,7 @@ class TestBridge: deleted = None def _read_all(self, sql, params): - assert "session_key" in sql and params == (session_key, "pheby") + assert "session_key" in sql and params == (session_key, "pheby", "pheby_delivery") return [{"id": "session-old"}, {"id": "session-delete"}] def delete_sessions(self, session_ids):