fix(pheby): persist cron deliveries in chat display history

This commit is contained in:
2026-10-30 12:15:09 +00:00
parent 7b94342eb8
commit 7e0e510bac
4 changed files with 196 additions and 5 deletions
+12
View File
@@ -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"):
+74 -4
View File
@@ -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: