From 9d1e0398fff2272a0d1858a4a2b9c848d4206886 Mon Sep 17 00:00:00 2001 From: Test Date: Tue, 24 Nov 2026 16:02:32 +0800 Subject: [PATCH] fix(proactive): persist care messages to thread history and track replies Fixes #3064 --- src/octop/infra/db/migrate.py | 34 +++ src/octop/infra/db/repos/care_push.py | 178 +++++++++++- src/octop/infra/db/repos/thread_messages.py | 21 ++ src/octop/infra/gateway/gateway.py | 2 + src/octop/infra/gateway/hitl/store.py | 13 + src/octop/infra/gateway/process/processor.py | 53 ++++ src/octop/infra/proactive/scheduler.py | 152 ++++++++-- src/octop/infra/proactive/service.py | 153 +++++++++- src/octop/infra/server.py | 4 + .../proactive/test_care_reply_tracking.py | 194 +++++++++++++ .../unit/proactive/test_proactive_service.py | 269 +++++++++++++++++- tests/unit/proactive/test_scheduler.py | 186 ++++++++++++ 12 files changed, 1216 insertions(+), 43 deletions(-) create mode 100644 tests/unit/proactive/test_care_reply_tracking.py diff --git a/src/octop/infra/db/migrate.py b/src/octop/infra/db/migrate.py index 91c62a206a..b032d94b32 100644 --- a/src/octop/infra/db/migrate.py +++ b/src/octop/infra/db/migrate.py @@ -1821,6 +1821,39 @@ def _ensure_thread_contributed_schema(db: DatabasePool) -> None: _ensure_column(db, "threads", "contributed", "INTEGER NOT NULL DEFAULT 0") +def _ensure_care_push_reply_schema(db: DatabasePool) -> None: + """Proactive care thread/message/reply tracking on ``care_push_records``. Idempotent.""" + if not _table_exists(db, "care_push_records"): + return + ts_type = "BIGINT" if db.dialect == "postgresql" else "INTEGER" + _ensure_column(db, "care_push_records", "thread_id", "TEXT") + _ensure_column(db, "care_push_records", "message_id", "TEXT") + _ensure_column(db, "care_push_records", "care_text", "TEXT") + _ensure_column(db, "care_push_records", "status", "TEXT NOT NULL DEFAULT 'sent'") + _ensure_column(db, "care_push_records", "replied_at", ts_type) + _ensure_column(db, "care_push_records", "reply_message_id", "TEXT") + if db.dialect == "postgresql": + with db.connect() as conn, conn.transaction(): + conn.execute( + "CREATE INDEX IF NOT EXISTS idx_care_push_thread_status " + "ON care_push_records(thread_id, status, pushed_at)" + ) + conn.execute( + "CREATE INDEX IF NOT EXISTS idx_care_push_agent_status " + "ON care_push_records(agent_id, status, pushed_at)" + ) + return + with db.transaction() as conn: + conn.execute( + "CREATE INDEX IF NOT EXISTS idx_care_push_thread_status " + "ON care_push_records(thread_id, status, pushed_at)" + ) + conn.execute( + "CREATE INDEX IF NOT EXISTS idx_care_push_agent_status " + "ON care_push_records(agent_id, status, pushed_at)" + ) + + _LOGIN_AUDIT_ACTIONS_SQL = ( "'auth.login', 'auth.ldap_login', 'auth.oidc_login', 'auth.passkey_login'" ) @@ -2805,6 +2838,7 @@ def run_migrations(db: DatabasePool) -> None: _ensure_instance_lease_schema(db) _ensure_control_blobs_schema(db) _ensure_thread_contributed_schema(db) + _ensure_care_push_reply_schema(db) _ensure_invite_redemptions_schema(db) _grant_default_nav_permissions(db) _grant_personalization_tab_permissions(db) diff --git a/src/octop/infra/db/repos/care_push.py b/src/octop/infra/db/repos/care_push.py index 83998a2107..5c62f217f5 100644 --- a/src/octop/infra/db/repos/care_push.py +++ b/src/octop/infra/db/repos/care_push.py @@ -1,7 +1,8 @@ """Data-access layer for the proactive care push records table. The care_push_records table records the episode_id consumed by each proactive_care -push, used to avoid re-pushing the same event within 30 days. +push (used for 30-day dedup) along with delivery coordinates (thread_id, message_id) +and user reply status for backoff and downstream memory feedback. """ from __future__ import annotations @@ -9,8 +10,43 @@ import time import uuid from collections.abc import Sequence +from dataclasses import dataclass from octop.infra.db.pool import DatabasePool +from octop.infra.db.repos._base import DbRow + + +@dataclass(frozen=True) +class CarePushRecord: + """One row from ``care_push_records``.""" + + id: str + agent_id: str + session_key: str + episode_id: str + pushed_at: int + thread_id: str | None = None + message_id: str | None = None + care_text: str | None = None + status: str = "sent" + replied_at: int | None = None + reply_message_id: str | None = None + + @classmethod + def from_row(cls, row: DbRow) -> CarePushRecord: + return cls( + id=str(row["id"]), + agent_id=str(row["agent_id"]), + session_key=str(row["session_key"]), + episode_id=str(row["episode_id"]), + pushed_at=int(row["pushed_at"]), + thread_id=str(row["thread_id"]) if row["thread_id"] else None, + message_id=str(row["message_id"]) if row["message_id"] else None, + care_text=str(row["care_text"]) if row["care_text"] is not None else None, + status=str(row["status"] or "sent"), + replied_at=int(row["replied_at"]) if row["replied_at"] is not None else None, + reply_message_id=str(row["reply_message_id"]) if row["reply_message_id"] else None, + ) class CarePushRepo: @@ -26,26 +62,158 @@ def insert( session_key: str, episode_ids: Sequence[str], pushed_at: int | None = None, + thread_id: str | None = None, + message_id: str | None = None, + care_text: str | None = None, ) -> None: - """Batch-insert push records. + """Batch-insert push records for one proactive care delivery. Args: agent_id: The agent ID the push belongs to. session_key: The session key the push belongs to. episode_ids: The list of episode IDs consumed by this push. pushed_at: Push timestamp (unix); defaults to the current time. + thread_id: Target thread ID where the care message was stored. + message_id: Canonical ``AIMessage.id`` stored in the thread. + care_text: Delivered care text (for reply correlation and feedback). """ if not episode_ids: return ts = pushed_at if pushed_at is not None else int(time.time()) - rows = [(str(uuid.uuid4()), agent_id, session_key, ep_id, ts) for ep_id in episode_ids] + rows = [ + ( + str(uuid.uuid4()), + agent_id, + session_key, + ep_id, + ts, + thread_id, + message_id, + care_text, + "sent", + ) + for ep_id in episode_ids + ] with self._db.transaction() as conn: conn.executemany( - "INSERT INTO care_push_records(id, agent_id, session_key, episode_id, pushed_at) " - "VALUES (?, ?, ?, ?, ?)", + "INSERT INTO care_push_records(" + "id, agent_id, session_key, episode_id, pushed_at, " + "thread_id, message_id, care_text, status" + ") VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)", rows, ) + def mark_replied_for_thread( + self, + *, + agent_id: str, + thread_id: str, + reply_message_id: str | None = None, + replied_at: int | None = None, + ) -> int: + """Record that the user replied in *thread_id* after a proactive care push. + + The latest open (``status='sent'``) care push in *thread_id* is marked + ``'replied'``; any older still-open pushes in the same thread are marked + ``'ignored'`` so reply attribution stays tied to the message the user saw. + + Returns: + Number of rows marked ``'replied'``. + """ + tid = thread_id.strip() + if not tid: + return 0 + ts = replied_at if replied_at is not None else int(time.time()) + with self._db.transaction() as conn: + latest = conn.execute( + "SELECT message_id, pushed_at FROM care_push_records " + "WHERE agent_id = ? AND thread_id = ? AND status = 'sent' AND pushed_at <= ? " + "ORDER BY pushed_at DESC LIMIT 1", + (agent_id, tid, ts), + ).fetchone() + if latest is None: + return 0 + latest_mid = latest["message_id"] + latest_pushed_at = int(latest["pushed_at"]) + if latest_mid: + cur = conn.execute( + "UPDATE care_push_records " + "SET status = 'replied', replied_at = ?, reply_message_id = ? " + "WHERE agent_id = ? AND thread_id = ? AND status = 'sent' " + "AND message_id = ?", + (ts, reply_message_id, agent_id, tid, latest_mid), + ) + replied_count = int(cur.rowcount or 0) + conn.execute( + "UPDATE care_push_records " + "SET status = 'ignored' " + "WHERE agent_id = ? AND thread_id = ? AND status = 'sent' " + "AND pushed_at <= ? AND (message_id IS NULL OR message_id <> ?)", + (agent_id, tid, ts, latest_mid), + ) + else: + cur = conn.execute( + "UPDATE care_push_records " + "SET status = 'replied', replied_at = ?, reply_message_id = ? " + "WHERE agent_id = ? AND thread_id = ? AND status = 'sent' " + "AND pushed_at = ?", + (ts, reply_message_id, agent_id, tid, latest_pushed_at), + ) + replied_count = int(cur.rowcount or 0) + conn.execute( + "UPDATE care_push_records " + "SET status = 'ignored' " + "WHERE agent_id = ? AND thread_id = ? AND status = 'sent' " + "AND pushed_at < ?", + (agent_id, tid, latest_pushed_at), + ) + return replied_count + + def count_consecutive_unanswered(self, agent_id: str, *, limit: int = 20) -> int: + """Count consecutive recent care pushes for *agent_id* without a reply. + + Multiple episode rows emitted by the same delivery (sharing ``message_id``, + or ``(pushed_at, session_key)`` for legacy rows) are collapsed into one push. + """ + with self._db.connect() as conn: + rows = conn.execute( + "SELECT message_id, pushed_at, session_key, status " + "FROM care_push_records " + "WHERE agent_id = ? " + "ORDER BY pushed_at DESC LIMIT ?", + (agent_id, max(limit * 3, 30)), + ).fetchall() + seen_keys: list[tuple[str, int, str]] = [] + push_replied: dict[tuple[str, int, str], bool] = {} + for row in rows: + mid = str(row["message_id"] or "") + key = (mid, int(row["pushed_at"]), str(row["session_key"])) if not mid else (mid, 0, "") + if key not in push_replied: + if len(seen_keys) >= limit: + break + seen_keys.append(key) + push_replied[key] = False + if str(row["status"] or "sent") == "replied": + push_replied[key] = True + streak = 0 + for key in seen_keys: + if push_replied[key]: + break + streak += 1 + return streak + + def list_recent(self, agent_id: str, *, limit: int = 20) -> list[CarePushRecord]: + """Return the most recent care push rows for *agent_id*.""" + with self._db.connect() as conn: + rows = conn.execute( + "SELECT id, agent_id, session_key, episode_id, pushed_at, " + "thread_id, message_id, care_text, status, replied_at, reply_message_id " + "FROM care_push_records WHERE agent_id = ? " + "ORDER BY pushed_at DESC LIMIT ?", + (agent_id, limit), + ).fetchall() + return [CarePushRecord.from_row(r) for r in rows] + def latest_pushed_at(self, agent_id: str) -> int | None: """Unix time of the most recent care push for ``agent_id``, if any.""" with self._db.connect() as conn: diff --git a/src/octop/infra/db/repos/thread_messages.py b/src/octop/infra/db/repos/thread_messages.py index f0c78ec697..604c35de6e 100644 --- a/src/octop/infra/db/repos/thread_messages.py +++ b/src/octop/infra/db/repos/thread_messages.py @@ -67,6 +67,27 @@ def head(self, thread_id: str) -> int: ).fetchone() return int(row[0]) + def latest_human_activity(self, agent_id: str) -> int | None: + """Latest real human message timestamp (unix seconds) for *agent_id*. + + Excludes synthetic cron prompts (``cron:%``) so scheduled runs and + proactive care messages do not distort the user-idle clock. + """ + with self._db.connect() as conn: + row = conn.execute( + "SELECT MAX(tm.created_at) " + "FROM thread_messages tm " + "JOIN threads t ON t.thread_id = tm.thread_id " + "WHERE t.agent_id = ? " + "AND tm.role IN ('human', 'user') " + "AND (tm.message_id IS NULL OR tm.message_id NOT LIKE 'cron:%')", + (agent_id,), + ).fetchone() + if row is None or row[0] is None: + return None + ts = int(row[0]) + return ts if ts > 0 else None + def threads_with_messages(self, thread_ids: Sequence[str]) -> set[str]: """Which of *thread_ids* actually have projected messages. diff --git a/src/octop/infra/gateway/gateway.py b/src/octop/infra/gateway/gateway.py index 3579325745..c3d30b8c44 100644 --- a/src/octop/infra/gateway/gateway.py +++ b/src/octop/infra/gateway/gateway.py @@ -152,6 +152,7 @@ def replace_repos(self, repos: RepoBundle) -> None: ) if self._processor is not None: self._processor.replace_thread_message_repo(repos.thread_message_repo) + self._processor.replace_care_push_repo(repos.care_push_repo) self._processor.hitl_coordinator.session_policies.replace_repo(repos.thread_repo) @property @@ -286,6 +287,7 @@ async def boot(self, *, serve_background: bool = True) -> None: dispatcher=self._dispatcher, usage_repo=self._repos.usage_repo, thread_message_repo=self._repos.thread_message_repo, + care_push_repo=self._repos.care_push_repo, gateway=self, trajectory_service=self._trajectory_service, ) diff --git a/src/octop/infra/gateway/hitl/store.py b/src/octop/infra/gateway/hitl/store.py index 671dfa3eeb..79b080b9ba 100644 --- a/src/octop/infra/gateway/hitl/store.py +++ b/src/octop/infra/gateway/hitl/store.py @@ -295,6 +295,19 @@ def pending_thread_ids( out.add(tid) return frozenset(out) + def has_pending_for_agent(self, agent_id: str) -> bool: + """Whether *agent_id* has any live pending HITL pause across all users.""" + self._gc() + now = time.time() + for record in self._records.values(): + if record.status != "pending": + continue + if now - record.created_at > self.ttl_seconds: + continue + if record.agent_id == agent_id or record.resume_agent_id == agent_id: + return True + return False + def expire_pending_for_thread( self, thread_id: str, diff --git a/src/octop/infra/gateway/process/processor.py b/src/octop/infra/gateway/process/processor.py index 2f781d3dff..818a15d86c 100644 --- a/src/octop/infra/gateway/process/processor.py +++ b/src/octop/infra/gateway/process/processor.py @@ -188,6 +188,7 @@ def __init__( dispatcher: SlashDispatcher, usage_repo: Any | None = None, thread_message_repo: Any | None = None, + care_push_repo: Any | None = None, gateway: Any | None = None, hitl: HitlChannelCoordinator | None = None, trajectory_service: Any | None = None, @@ -210,6 +211,7 @@ def __init__( self._dispatcher = dispatcher self._usage_repo = usage_repo self._thread_message_repo = thread_message_repo + self._care_push_repo = care_push_repo self._gateway = gateway self._hitl = hitl or HitlChannelCoordinator() self._trajectory_service = trajectory_service @@ -239,6 +241,47 @@ def replace_thread_message_repo(self, repo: Any) -> None: self._thread_message_repo = repo self.teams.replace_thread_message_repo(repo) + def replace_care_push_repo(self, repo: Any) -> None: + """Rebind proactive care reply tracking after a control-plane restore.""" + self._care_push_repo = repo + + def _mark_care_replied( + self, + *, + agent_id: str, + thread_id: str, + history_tracker: TurnHistoryTracker, + ) -> None: + if self._care_push_repo is None: + return + reply_msg_id: str | None = None + for seed in history_tracker.seed_messages: + mid = seed.get("id") if isinstance(seed, dict) else getattr(seed, "id", None) + if isinstance(mid, str) and mid.strip(): + reply_msg_id = mid.strip() + break + try: + updated = self._care_push_repo.mark_replied_for_thread( + agent_id=agent_id, + thread_id=thread_id, + reply_message_id=reply_msg_id, + ) + if updated: + logger.info( + "ProactiveCare: marked %d record(s) replied agent=%s thread=%s reply_msg=%s", + updated, + agent_id, + thread_id, + reply_msg_id, + ) + except Exception: + logger.warning( + "ProactiveCare: failed to mark reply agent=%s thread=%s", + agent_id, + thread_id, + exc_info=True, + ) + def _agent_trajectory_enabled(self, agent_id: str, row: Any | None = None) -> bool: if self._trajectory_service is None: return False @@ -1082,6 +1125,11 @@ async def __call__(self, msg: InboundMessage) -> AsyncIterator[MessageEvent]: failure_saved = False usage_tracker = UsageTracker() history_tracker = TurnHistoryTracker.from_request(request) + self._mark_care_replied( + agent_id=agent_id, + thread_id=thread_id, + history_tracker=history_tracker, + ) projection_state = StreamProjectionState() try: turn_stream = project_stream( @@ -1389,6 +1437,11 @@ async def iter_turn_chunks(self, msg: InboundMessage) -> AsyncIterator[dict[str, meta=meta, ) history_tracker = TurnHistoryTracker.from_request(request) + self._mark_care_replied( + agent_id=agent_id, + thread_id=thread_id, + history_tracker=history_tracker, + ) self._observe_trajectory( agent_id=agent_id, thread_id=thread_id, diff --git a/src/octop/infra/proactive/scheduler.py b/src/octop/infra/proactive/scheduler.py index 03ba112fa7..c439c9c394 100644 --- a/src/octop/infra/proactive/scheduler.py +++ b/src/octop/infra/proactive/scheduler.py @@ -15,11 +15,13 @@ import asyncio import logging import random -from collections.abc import Callable +from collections.abc import Callable, Sequence from datetime import UTC, datetime, time, timedelta from typing import TYPE_CHECKING from zoneinfo import ZoneInfo, ZoneInfoNotFoundError +from octop.infra.gateway.threads import ThreadRegistry + if TYPE_CHECKING: from octop.infra.db.repos.agents import AgentRepo from octop.infra.db.repos.care_push import CarePushRepo @@ -27,7 +29,8 @@ ProactiveCareConfig, ProactiveCareConfigRepo, ) - from octop.infra.db.repos.sessions import SessionRepo + from octop.infra.db.repos.sessions import SessionRepo, SessionRow + from octop.infra.db.repos.thread_messages import ThreadMessageRepo from octop.infra.db.repos.threads import ThreadRepo from octop.infra.db.repos.users import UserRepo from octop.infra.proactive.service import ProactiveCareService @@ -44,6 +47,52 @@ _BUSY_RETRY = timedelta(minutes=15) # Smear only the "window just opened" wake so agents don't all fire on the minute. _OPEN_JITTER_MINUTES = 15 +_MAX_BACKOFF_HOURS = 168 # 7 days + + +def select_care_target_session(sessions: Sequence[SessionRow]) -> SessionRow | None: + """Choose the best DM target session for proactive care. + + Priority: + 1. Most recently updated IM direct-message session (excludes MCP / CLI / group / peer / team). + 2. Most recently updated Dashboard direct-message session. + Returns ``None`` when no eligible private session exists. + """ + for session in sessions: + if ( + ThreadRegistry.is_im_session(session) + and session.chat_type == ThreadRegistry.CHAT_TYPE_DM + ): + return session + for session in sessions: + if ( + session.channel_type == ThreadRegistry.CHANNEL_DASHBOARD + and session.chat_type == ThreadRegistry.CHAT_TYPE_DM + ): + return session + return None + + +def backoff_interval_hours( + min_interval_hours: int, + max_interval_hours: int, + unanswered_streak: int, +) -> tuple[int, int]: + """Scale the random push interval when consecutive care pushes went unanswered. + + - 0 or 1 unanswered push: normal interval (1x) + - 2 unanswered pushes: 2x + - 3+ unanswered pushes: 4x (capped at ``_MAX_BACKOFF_HOURS``) + """ + if unanswered_streak < 2: + return min_interval_hours, max_interval_hours + multiplier = 2 if unanswered_streak == 2 else 4 + cap = max(_MAX_BACKOFF_HOURS, max_interval_hours) + scaled_min = min(min_interval_hours * multiplier, cap) + scaled_max = min(max_interval_hours * multiplier, cap) + if scaled_min > scaled_max: + scaled_min = scaled_max + return scaled_min, scaled_max def _parse_hhmm(hhmm: str) -> time: @@ -286,8 +335,10 @@ def __init__( agent_repo: AgentRepo | None = None, user_repo: UserRepo | None = None, thread_repo: ThreadRepo | None = None, + thread_message_repo: ThreadMessageRepo | None = None, care_push_repo: CarePushRepo | None = None, is_agent_busy: Callable[[str], bool] | None = None, + has_pending_hitl: Callable[[str], bool] | None = None, default_timezone: str = _UTC_TZ_NAME, ) -> None: self._care_service = care_service @@ -296,8 +347,10 @@ def __init__( self._agent_repo = agent_repo self._user_repo = user_repo self._thread_repo = thread_repo + self._thread_message_repo = thread_message_repo self._care_push_repo = care_push_repo self._is_agent_busy = is_agent_busy + self._has_pending_hitl = has_pending_hitl self._default_timezone = default_timezone # agent_id -> asyncio.Task self._tasks: dict[str, asyncio.Task[None]] = {} @@ -310,6 +363,7 @@ def replace_persistence( session_repo: SessionRepo, care_push_repo: CarePushRepo, thread_repo: ThreadRepo | None = None, + thread_message_repo: ThreadMessageRepo | None = None, ) -> None: """Point scheduler/care persistence at a rebound control-plane pool.""" self._config_repo = config_repo @@ -317,7 +371,12 @@ def replace_persistence( self._care_push_repo = care_push_repo if thread_repo is not None: self._thread_repo = thread_repo - self._care_service.replace_care_push_repo(care_push_repo) + if thread_message_repo is not None: + self._thread_message_repo = thread_message_repo + self._care_service.replace_care_push_repo( + care_push_repo, + thread_message_repo=thread_message_repo, + ) async def start_all(self) -> None: """At system startup, register random scheduling tasks for all agents with enabled=true. @@ -448,12 +507,27 @@ async def _run_loop(self, agent_id: str) -> None: timezone_name = self._resolve_tz_for_agent(agent_id) if hold_until is None: + unanswered = self._consecutive_unanswered(agent_id) + eff_min, eff_max = backoff_interval_hours( + cfg.min_interval_hours, + cfg.max_interval_hours, + unanswered, + ) + if eff_min != cfg.min_interval_hours or eff_max != cfg.max_interval_hours: + logger.info( + "ProactiveCareScheduler: agent=%s applying reply backoff " + "(unanswered=%d, interval=%d-%dh)", + agent_id, + unanswered, + eff_min, + eff_max, + ) hold_until = compute_next_trigger( now=now, active_hours_start=cfg.active_hours_start, active_hours_end=cfg.active_hours_end, - min_interval_hours=cfg.min_interval_hours, - max_interval_hours=cfg.max_interval_hours, + min_interval_hours=eff_min, + max_interval_hours=eff_max, timezone_name=timezone_name, ) wait_seconds = (hold_until - now).total_seconds() @@ -504,21 +578,16 @@ async def _run_loop(self, agent_id: str) -> None: ) continue - sessions = self._session_repo.list_by_agent(agent_id, limit=10) - if not sessions: + sessions = self._session_repo.list_by_agent(agent_id, limit=50) + target_session = select_care_target_session(sessions) + if target_session is None: logger.info( - "ProactiveCareScheduler: agent=%s has no active session, skipping this push", + "ProactiveCareScheduler: agent=%s has no eligible DM session, skipping this push", agent_id, ) hold_until = None continue - # Prefer an IM session (non-empty channel_id), otherwise the most recently active one. - target_session = next( - (s for s in sessions if s.channel_id), - sessions[0], - ) - def can_send( bound_cfg: ProactiveCareConfig = cfg, bound_tz: str = timezone_name, @@ -547,14 +616,18 @@ def _timing_decision( timezone_name: str, now: datetime, ) -> TimingDecision: + last_active_at, exact_human = self._latest_activity(agent_id) + # Real human message timestamps from thread_messages never include our + # own care push or cron turns, so omit the legacy push-slack heuristic. + last_push_at = None if exact_human else self._latest_push(agent_id) return decide_send_timing( now=now, active_hours_start=cfg.active_hours_start, active_hours_end=cfg.active_hours_end, timezone_name=timezone_name, - last_active_at=self._latest_activity(agent_id), - last_push_at=self._latest_push(agent_id), - agent_busy=self._agent_is_busy(agent_id), + last_active_at=last_active_at, + last_push_at=last_push_at, + agent_busy=self._agent_is_busy(agent_id) or self._agent_has_pending_hitl(agent_id), ) def _moment_is_good( @@ -565,18 +638,42 @@ def _moment_is_good( ) -> bool: return self._timing_decision(agent_id, cfg, timezone_name, datetime.now(UTC)).send - def _latest_activity(self, agent_id: str) -> int | None: + def _latest_activity(self, agent_id: str) -> tuple[int | None, bool]: + if self._thread_message_repo is not None: + try: + human_ts = self._thread_message_repo.latest_human_activity(agent_id) + if human_ts is not None: + return human_ts, True + except Exception: + logger.warning( + "ProactiveCareScheduler: agent=%s failed to read human activity", + agent_id, + exc_info=True, + ) if self._thread_repo is None: - return None + return None, False try: - return self._thread_repo.latest_user_activity(agent_id) + return self._thread_repo.latest_user_activity(agent_id), False except Exception: logger.warning( "ProactiveCareScheduler: agent=%s failed to read last activity", agent_id, exc_info=True, ) - return None + return None, False + + def _consecutive_unanswered(self, agent_id: str) -> int: + if self._care_push_repo is None: + return 0 + try: + return self._care_push_repo.count_consecutive_unanswered(agent_id) + except Exception: + logger.warning( + "ProactiveCareScheduler: agent=%s failed to read unanswered care streak", + agent_id, + exc_info=True, + ) + return 0 def _latest_push(self, agent_id: str) -> int | None: if self._care_push_repo is None: @@ -604,6 +701,19 @@ def _agent_is_busy(self, agent_id: str) -> bool: ) return False + def _agent_has_pending_hitl(self, agent_id: str) -> bool: + if self._has_pending_hitl is None: + return False + try: + return self._has_pending_hitl(agent_id) is True + except Exception: + logger.warning( + "ProactiveCareScheduler: agent=%s failed to read pending HITL state", + agent_id, + exc_info=True, + ) + return False + def _resolve_tz_for_agent(self, agent_id: str) -> str: if self._agent_repo is None or self._user_repo is None: return self._default_timezone diff --git a/src/octop/infra/proactive/service.py b/src/octop/infra/proactive/service.py index 92a975d769..f45519269d 100644 --- a/src/octop/infra/proactive/service.py +++ b/src/octop/infra/proactive/service.py @@ -6,28 +6,37 @@ 3. Use EpisodePicker to select the Top-3 most care-worthy episodes. 4. Read the agent's SOUL.md and embed it into the LLM system prompt. 5. Call a lightweight LLM to generate a care message (<=200 chars). -6. Push to the current session via Gateway.push_text_from_session. -7. Write a dedup record to care_push_records after a successful push. +6. Under the session lock, bind the latest active thread, append a single + AIMessage to the harness checkpoint and thread_messages projection, push + over the session transport, and (for dashboard) send the toast notification. +7. Write push + reply-tracking records to care_push_records after delivery. """ from __future__ import annotations import logging from collections.abc import Callable +from dataclasses import dataclass from datetime import UTC, datetime, timedelta from typing import TYPE_CHECKING, Any from zoneinfo import ZoneInfo -from langchain_core.messages import HumanMessage, SystemMessage +from langchain_core.messages import AIMessage, HumanMessage, SystemMessage from octop.i18n.loader import tr as i18n_tr +from octop.infra.db.repos.threads import ThreadRow +from octop.infra.gateway.threads import ThreadRegistry +from octop.infra.history.projection import message_inputs from octop.infra.proactive.picker import EpisodePicker from octop.infra.utils.llm_text import ainvoke_text from octop.infra.utils.locale import normalize_locale +from octop.infra.utils.ulid import new_ulid if TYPE_CHECKING: from octop.infra.agents.manager import AgentManager from octop.infra.db.repos.care_push import CarePushRepo + from octop.infra.db.repos.sessions import SessionRow + from octop.infra.db.repos.thread_messages import ThreadMessageRepo from octop.infra.gateway.gateway import Gateway logger = logging.getLogger(__name__) @@ -81,6 +90,14 @@ def _format_episodes_for_prompt(episodes: list[Any]) -> str: # --------------------------------------------------------------------------- +@dataclass(frozen=True) +class _DeliveredCare: + """Delivery coordinates recorded after persisting and pushing a care message.""" + + thread_id: str + message_id: str + + class ProactiveCareService: """Proactive care push service. @@ -89,8 +106,9 @@ class ProactiveCareService: Args: gateway: Gateway instance used to push messages. - care_push_repo: CarePushRepo instance used for dedup records. + care_push_repo: CarePushRepo instance used for dedup and reply tracking. agent_manager: AgentManager instance used to obtain HarnessAgent and Memory. + thread_message_repo: Optional ThreadMessageRepo for dashboard history projection. """ def __init__( @@ -99,11 +117,13 @@ def __init__( gateway: Gateway, care_push_repo: CarePushRepo, agent_manager: AgentManager, + thread_message_repo: ThreadMessageRepo | None = None, timezone: str = "Asia/Shanghai", ) -> None: self._gateway = gateway self._care_push_repo = care_push_repo self._agent_manager = agent_manager + self._thread_message_repo = thread_message_repo self._timezone = timezone or "Asia/Shanghai" self._picker = EpisodePicker( top_k=3, @@ -111,9 +131,110 @@ def __init__( fallback_days=_FALLBACK_WINDOW_DAYS, ) - def replace_care_push_repo(self, care_push_repo: CarePushRepo) -> None: - """Point dedup storage at a rebound control-plane pool.""" + def replace_care_push_repo( + self, + care_push_repo: CarePushRepo, + thread_message_repo: ThreadMessageRepo | None = None, + ) -> None: + """Point dedup and history projection storage at a rebound control-plane pool.""" self._care_push_repo = care_push_repo + if thread_message_repo is not None: + self._thread_message_repo = thread_message_repo + + async def _bind_latest_thread(self, session_key: str) -> None: + """Point *session_key* at its latest active conversation, skipping blank threads.""" + registry = self._gateway.thread_registry + latest = registry.latest_active_thread(session_key=session_key) + if not isinstance(latest, ThreadRow): + return + if registry.get_bound_thread_id(session_key) == latest.thread_id: + return + session = registry.get_session(session_key) + if session is None: + return + await registry.rebind( + session_key=session_key, + thread_id=latest.thread_id, + agent_id=session.agent_id, + acting_user_id=session.user_id, + ) + + def _project_best_effort(self, thread_id: str, appended: list[Any]) -> None: + if self._thread_message_repo is None or not appended: + return + try: + self._thread_message_repo.append_if_ready( + thread_id, + message_inputs(appended, dedupe_missing_ids=True), + ) + except Exception: + logger.warning( + "ProactiveCareService: failed to append history projection thread=%s", + thread_id, + exc_info=True, + ) + + async def _notify_best_effort( + self, + session: SessionRow, + agent_id: str, + text: str, + ) -> None: + if session.channel_type != ThreadRegistry.CHANNEL_DASHBOARD: + return + try: + await self._gateway.notify_dashboard_push(session, agent_id, text) + except Exception: + logger.warning( + "ProactiveCareService: failed to send dashboard notification thread=%s", + session.thread_id, + exc_info=True, + ) + + async def _deliver( + self, + agent_id: str, + session_key: str, + care_text: str, + *, + can_send: Callable[[], bool] | None = None, + ) -> _DeliveredCare | None: + """Persist a single AIMessage to checkpoint + projection, then push it. + + ``Gateway.push_text_from_session`` is transport-only; persisting here + keeps dashboard history, unread badges, and next-turn agent context in + sync across both dashboard and IM sessions. + """ + delivered: _DeliveredCare | None = None + + async def _locked() -> None: + nonlocal delivered + if can_send is not None and not can_send(): + logger.info( + "ProactiveCareService: user activity changed before locked delivery, " + "discarding agent=%s", + agent_id, + ) + return + await self._bind_latest_thread(session_key) + session = self._gateway.require_session(agent_id, session_key) + message_id = f"care:{new_ulid()}:assistant" + harness = self._agent_manager.get_agent(agent_id) + appended = await harness.aappend_messages( + session.thread_id, + [AIMessage(content=care_text, id=message_id)], + ) + self._project_best_effort(session.thread_id, appended) + await self._gateway.push_session_text( + session, + care_text, + title_source=care_text, + ) + await self._notify_best_effort(session, agent_id, care_text) + delivered = _DeliveredCare(thread_id=session.thread_id, message_id=message_id) + + await self._gateway.run_in_session(agent_id, session_key, _locked) + return delivered async def run( self, @@ -257,7 +378,7 @@ async def run( logger.warning("ProactiveCareService: LLM call failed agent=%s: %s", agent_id, exc) return # do not push, do not write a record - # 7. Push the message directly without invoking the agent. + # 7. Persist and push the message directly without invoking the agent. if can_send is not None and not can_send(): logger.info( "ProactiveCareService: user activity changed during generation, discarding agent=%s", @@ -265,7 +386,12 @@ async def run( ) return try: - await self._gateway.push_text_from_session(agent_id, session_key, care_text) + delivered = await self._deliver( + agent_id, + session_key, + care_text, + can_send=can_send, + ) except Exception as exc: logger.warning( "ProactiveCareService: push failed agent=%s session=%s: %s", @@ -275,13 +401,19 @@ async def run( ) return # do not write a record - # 8. Write the dedup record (only after a successful push) + if delivered is None: + return + + # 8. Write dedup + reply-tracking records (only after a successful push) episode_ids = [ep.id for ep in pick_result.episodes] try: self._care_push_repo.insert( agent_id=agent_id, session_key=session_key, episode_ids=episode_ids, + thread_id=delivered.thread_id, + message_id=delivered.message_id, + care_text=care_text, ) except Exception as exc: # A failed write does not affect the push result; just log it @@ -290,9 +422,10 @@ async def run( ) logger.info( - "ProactiveCareService: push succeeded agent=%s session=%s episodes=%d window_days=%d", + "ProactiveCareService: push succeeded agent=%s session=%s thread=%s episodes=%d window_days=%d", agent_id, session_key, + delivered.thread_id, len(episode_ids), pick_result.window_days, ) diff --git a/src/octop/infra/server.py b/src/octop/infra/server.py index efb499ef2b..aba050e2a6 100644 --- a/src/octop/infra/server.py +++ b/src/octop/infra/server.py @@ -307,6 +307,7 @@ def replace_services(self, services: SharedServices, config: OctopConfig) -> Non session_repo=services.repos.session_repo, care_push_repo=services.repos.care_push_repo, thread_repo=services.repos.thread_repo, + thread_message_repo=services.repos.thread_message_repo, ) if self.trajectory_service is not None: from octop.infra.history.trajectory.store import TrajectoryStore # noqa: PLC0415 @@ -608,6 +609,7 @@ async def _boot_runtime(self, config: OctopConfig) -> None: gateway=gateway, care_push_repo=self.services.repos.care_push_repo, agent_manager=registry, + thread_message_repo=self.services.repos.thread_message_repo, timezone=config.default_timezone, ) proactive_scheduler = ProactiveCareScheduler( @@ -617,8 +619,10 @@ async def _boot_runtime(self, config: OctopConfig) -> None: agent_repo=self.services.repos.agent_repo, user_repo=self.services.repos.user_repo, thread_repo=self.services.repos.thread_repo, + thread_message_repo=self.services.repos.thread_message_repo, care_push_repo=self.services.repos.care_push_repo, is_agent_busy=registry.is_agent_active, + has_pending_hitl=gateway.processor.hitl_coordinator.store.has_pending_for_agent, default_timezone=config.default_timezone, ) registry.set_proactive_scheduler(proactive_scheduler) diff --git a/tests/unit/proactive/test_care_reply_tracking.py b/tests/unit/proactive/test_care_reply_tracking.py new file mode 100644 index 0000000000..ba81f0763a --- /dev/null +++ b/tests/unit/proactive/test_care_reply_tracking.py @@ -0,0 +1,194 @@ +"""Unit tests for Phase 2 proactive care reply tracking and HITL gating.""" + +from __future__ import annotations + +from pathlib import Path +from unittest.mock import MagicMock + +import pytest + +from octop.infra.db.migrate import run_migrations +from octop.infra.db.pool import SqlitePool +from octop.infra.db.repos.agents import AgentRepo +from octop.infra.db.repos.care_push import CarePushRepo +from octop.infra.db.repos.users import UserRepo +from octop.infra.gateway.hitl.store import HitlPendingStore +from octop.infra.gateway.process.processor import GlobalProcessor +from octop.infra.history.projection import TurnHistoryTracker +from octop.infra.utils.ulid import new_ulid + + +@pytest.fixture +def db(tmp_path: Path) -> SqlitePool: + pool = SqlitePool(tmp_path / "care_reply.db") + run_migrations(pool) + return pool + + +@pytest.fixture +def agent_id(db: SqlitePool) -> str: + uid = UserRepo(db).create(username="alice", password_hash="h", role="admin") + aid = new_ulid() + AgentRepo(db).create(agent_id=aid, user_id=uid, name="bot") + return aid + + +def test_mark_replied_updates_latest_push_and_ignores_older_open_pushes( + db: SqlitePool, + agent_id: str, +) -> None: + repo = CarePushRepo(db) + sk = f"{agent_id}:dashboard:1:dm" + + # First push (2 episodes) went unanswered. + repo.insert( + agent_id=agent_id, + session_key=sk, + episode_ids=["ep1", "ep2"], + pushed_at=1_700_000_100, + thread_id="thr_1", + message_id="care:push1:assistant", + care_text="第一条关怀", + ) + # Second push (1 episode) in the same thread. + repo.insert( + agent_id=agent_id, + session_key=sk, + episode_ids=["ep3"], + pushed_at=1_700_000_500, + thread_id="thr_1", + message_id="care:push2:assistant", + care_text="第二条关怀", + ) + assert repo.count_consecutive_unanswered(agent_id) == 2 + + # User replies in thr_1. + updated = repo.mark_replied_for_thread( + agent_id=agent_id, + thread_id="thr_1", + reply_message_id="human_msg_42", + replied_at=1_700_000_900, + ) + assert updated == 1 + assert repo.count_consecutive_unanswered(agent_id) == 0 + + by_mid: dict[str, list] = {} + for rec in repo.list_recent(agent_id): + by_mid.setdefault(rec.message_id or "", []).append(rec) + + assert len(by_mid["care:push2:assistant"]) == 1 + assert by_mid["care:push2:assistant"][0].status == "replied" + assert by_mid["care:push2:assistant"][0].replied_at == 1_700_000_900 + assert by_mid["care:push2:assistant"][0].reply_message_id == "human_msg_42" + + assert len(by_mid["care:push1:assistant"]) == 2 + assert all(r.status == "ignored" for r in by_mid["care:push1:assistant"]) + + # Another reply on the same thread is a no-op (no open 'sent' push left). + assert ( + repo.mark_replied_for_thread( + agent_id=agent_id, + thread_id="thr_1", + reply_message_id="human_msg_43", + replied_at=1_700_001_000, + ) + == 0 + ) + + +def test_consecutive_unanswered_resets_after_reply_and_counts_new_streak( + db: SqlitePool, + agent_id: str, +) -> None: + repo = CarePushRepo(db) + sk = f"{agent_id}:dashboard:1:dm" + + repo.insert( + agent_id=agent_id, + session_key=sk, + episode_ids=["ep1"], + pushed_at=1_700_000_100, + thread_id="thr_1", + message_id="care:p1:assistant", + ) + repo.mark_replied_for_thread( + agent_id=agent_id, + thread_id="thr_1", + replied_at=1_700_000_200, + ) + repo.insert( + agent_id=agent_id, + session_key=sk, + episode_ids=["ep2", "ep3"], + pushed_at=1_700_000_300, + thread_id="thr_1", + message_id="care:p2:assistant", + ) + repo.insert( + agent_id=agent_id, + session_key=sk, + episode_ids=["ep4"], + pushed_at=1_700_000_400, + thread_id="thr_2", + message_id="care:p3:assistant", + ) + + # p3 and p2 are unanswered; p1 was replied -> streak must be 2 (not 3 rows). + assert repo.count_consecutive_unanswered(agent_id) == 2 + + +def test_processor_mark_care_replied_hook(db: SqlitePool, agent_id: str) -> None: + repo = CarePushRepo(db) + repo.insert( + agent_id=agent_id, + session_key=f"{agent_id}:dashboard:1:dm", + episode_ids=["ep_hook"], + pushed_at=1_700_000_100, + thread_id="thr_care", + message_id="care:hook:assistant", + care_text="最近还好吗?", + ) + + proc = GlobalProcessor( + agent_manager=MagicMock(), + thread_registry=MagicMock(), + audit_repo=MagicMock(), + agent_repo=MagicMock(), + user_repo=MagicMock(), + connector_repo=MagicMock(), + dispatcher=MagicMock(), + care_push_repo=repo, + ) + tracker = TurnHistoryTracker.from_request( + {"messages": [{"role": "user", "id": "user_msg_99", "content": "好多了!"}]} + ) + # Reply in an unrelated thread does not mark thr_care replied. + proc._mark_care_replied(agent_id=agent_id, thread_id="thr_other", history_tracker=tracker) + assert repo.list_recent(agent_id)[0].status == "sent" + + # Reply in thr_care marks it replied with reply_message_id. + proc._mark_care_replied(agent_id=agent_id, thread_id="thr_care", history_tracker=tracker) + rec = repo.list_recent(agent_id)[0] + assert rec.status == "replied" + assert rec.reply_message_id == "user_msg_99" + assert rec.replied_at is not None + + +def test_hitl_store_has_pending_for_agent() -> None: + store = HitlPendingStore(ttl_seconds=600) + assert store.has_pending_for_agent("a1") is False + + rec = store.register( + agent_id="a1", + user_id=1, + thread_id="thr_1", + session_key="a1:dashboard:1:dm", + channel_type="dashboard", + action_requests=[{"name": "shell", "args": {"cmd": "ls"}}], + review_configs=None, + ) + assert store.has_pending_for_agent("a1") is True + assert store.has_pending_for_agent("a2") is False + + store.mark_resolved(rec.pending_id, status="approved") + assert store.has_pending_for_agent("a1") is False diff --git a/tests/unit/proactive/test_proactive_service.py b/tests/unit/proactive/test_proactive_service.py index f7bc04302b..b2ca31f8a6 100644 --- a/tests/unit/proactive/test_proactive_service.py +++ b/tests/unit/proactive/test_proactive_service.py @@ -21,7 +21,12 @@ from octop.infra.db.pool import SqlitePool from octop.infra.db.repos.agents import AgentRepo from octop.infra.db.repos.care_push import CarePushRepo +from octop.infra.db.repos.sessions import SessionRepo, SessionRow +from octop.infra.db.repos.thread_messages import ThreadMessageRepo +from octop.infra.db.repos.threads import ThreadRepo from octop.infra.db.repos.users import UserRepo +from octop.infra.gateway.gateway import Gateway +from octop.infra.gateway.threads import ThreadRegistry from octop.infra.proactive.service import ProactiveCareService from octop.infra.utils.ulid import new_ulid @@ -104,16 +109,51 @@ def _make_agent( config.default_model = "openai/gpt-4o-mini" config.locale = "zh-CN" agent.config = config + + # Mock checkpoint append (returns messages as-is). + async def _aappend(_thread_id: str, messages): + return list(messages) + + agent.aappend_messages = AsyncMock(side_effect=_aappend) return agent -def _make_gateway(push_success: bool = True) -> MagicMock: - """Create a mock Gateway.""" +def _make_gateway( + push_success: bool = True, + *, + channel_type: str = "wxwork", + thread_id: str = "thr_default", +) -> MagicMock: + """Create a mock Gateway wired for ProactiveCareService._deliver.""" gateway = MagicMock() + gateway.thread_registry = MagicMock() + gateway.thread_registry.latest_active_thread.return_value = None + + async def _run_in_session(_agent_id: str, _session_key: str, operation): + await operation() + + def _require_session(aid: str, sk: str) -> SessionRow: + return SessionRow( + id=1, + session_key=sk, + agent_id=aid, + user_id=1, + channel_type=channel_type, + chat_type="dm", + thread_id=thread_id, + updated_at=0, + channel_subject_id="user123", + channel_chat_type="dm", + channel_id="ch-1" if channel_type != "dashboard" else None, + ) + + gateway.run_in_session = AsyncMock(side_effect=_run_in_session) + gateway.require_session = MagicMock(side_effect=_require_session) + gateway.notify_dashboard_push = AsyncMock(return_value=None) if push_success: - gateway.push_text_from_session = AsyncMock(return_value=None) + gateway.push_session_text = AsyncMock(return_value=None) else: - gateway.push_text_from_session = AsyncMock(side_effect=RuntimeError("推送失败:网络错误")) + gateway.push_session_text = AsyncMock(side_effect=RuntimeError("推送失败:网络错误")) return gateway @@ -232,11 +272,11 @@ async def test_service_run_truncates_long_text(agent_id: str, care_push_repo: Ca # Capture the actual pushed text. pushed_texts: list[str] = [] - async def _capture_gen(agent_id: str, session_key: str, text: str, **kwargs): + async def _capture_push(_session, text: str, **kwargs): pushed_texts.append(text) - gateway = MagicMock() - gateway.push_text_from_session = _capture_gen + gateway = _make_gateway(push_success=True) + gateway.push_session_text = AsyncMock(side_effect=_capture_push) agent_manager = _make_agent_manager(agent) service = ProactiveCareService( gateway=gateway, @@ -299,3 +339,218 @@ async def test_service_run_no_memory(agent_id: str, care_push_repo: CarePushRepo # Verify no dedup records were written. pushed = care_push_repo.list_pushed_episode_ids(agent_id) assert len(pushed) == 0 + + +# --------------------------------------------------------------------------- +# Integration tests: persistence to checkpoint, thread_messages, and records +# --------------------------------------------------------------------------- + + +def _build_real_gateway(db: SqlitePool, agent: MagicMock) -> tuple[Gateway, MagicMock]: + agent_manager = _make_agent_manager(agent) + agent_manager.get_row.return_value = MagicMock(default_model=None) + agent_manager.get_row.return_value.name = "bot" + + repos = MagicMock() + repos.session_repo = SessionRepo(db) + repos.thread_repo = ThreadRepo(db) + repos.thread_message_repo = ThreadMessageRepo(db) + repos.user_repo = UserRepo(db) + + gateway = Gateway(agent_manager=agent_manager, repos=repos) + gateway._channel_manager = MagicMock() + gateway._channel_manager.push_text = AsyncMock(return_value=None) + gateway._channel_manager.get_channel = MagicMock(return_value=None) + + async def _run_in_session(_channel_id: str, _session_key: str, operation): + await operation() + + gateway._channel_manager.run_in_session = _run_in_session + return gateway, agent_manager + + +@pytest.mark.asyncio +async def test_dashboard_care_persists_ai_message_and_records_coordinates( + db: SqlitePool, + agent_id: str, + care_push_repo: CarePushRepo, +) -> None: + """Issue #3064: dashboard care writes a single AIMessage to checkpoint + thread_messages.""" + care_text = "昨天和经理聊得怎么样?记得好好休息。" + episodes = [_make_episode("ep_dash")] + checkpoint: list[tuple[str, str, str, str]] = [] + agent = _make_agent(episodes, llm_response=care_text) + + async def _aappend(tid: str, messages): + checkpoint.extend((tid, m.type, m.id, m.content) for m in messages) + return list(messages) + + agent.aappend_messages = AsyncMock(side_effect=_aappend) + gateway, agent_manager = _build_real_gateway(db, agent) + + session_key = ThreadRegistry.dashboard_key(agent_id=agent_id, user_id=1) + ThreadRepo(db).insert( + thread_id="thr_dash_active", + agent_id=agent_id, + user_id=1, + channel_type=ThreadRegistry.CHANNEL_DASHBOARD, + session_key=session_key, + last_active=1_700_000_000, + ) + # Also create a blank bound thread to ensure _bind_latest_thread prefers the active thread. + ThreadRepo(db).insert( + thread_id="thr_dash_blank", + agent_id=agent_id, + user_id=1, + channel_type=ThreadRegistry.CHANNEL_DASHBOARD, + session_key=session_key, + last_active=0, + ) + SessionRepo(db).upsert( + session_key=session_key, + agent_id=agent_id, + user_id=1, + channel_type=ThreadRegistry.CHANNEL_DASHBOARD, + chat_type=ThreadRegistry.CHAT_TYPE_DM, + thread_id="thr_dash_blank", + ) + + msg_repo = ThreadMessageRepo(db) + service = ProactiveCareService( + gateway=gateway, + care_push_repo=care_push_repo, + agent_manager=agent_manager, + thread_message_repo=msg_repo, + ) + await service.run(agent_id, session_key) + + # Persisted to checkpoint as a single AIMessage on the active thread. + assert len(checkpoint) == 1 + tid, role, mid, content = checkpoint[0] + assert tid == "thr_dash_active" + assert role == "ai" + assert mid.startswith("care:") and mid.endswith(":assistant") + assert content == care_text + + # Persisted to thread_messages projection so dashboard history shows it. + rows, _ = msg_repo.page("thr_dash_active", limit=10) + assert len(rows) == 1 + assert rows[0].role == "ai" + assert rows[0].message_id == mid + assert care_text in rows[0].message_json + + # Unread count bumped and care_push_records stores thread/message/text/status. + session = SessionRepo(db).get(session_key) + assert session is not None + assert session.thread_id == "thr_dash_active" + assert session.unread_count == 1 + + records = care_push_repo.list_recent(agent_id) + assert len(records) == 1 + assert records[0].thread_id == "thr_dash_active" + assert records[0].message_id == mid + assert records[0].care_text == care_text + assert records[0].status == "sent" + + +@pytest.mark.asyncio +async def test_im_care_persists_ai_message_for_reply_context( + db: SqlitePool, + agent_id: str, + care_push_repo: CarePushRepo, +) -> None: + """IM care also persists a single AIMessage so the agent remembers what it asked.""" + care_text = "这周加班辛苦了,今天早点歇着吧。" + checkpoint: list[tuple[str, str, str, str]] = [] + agent = _make_agent([_make_episode("ep_im")], llm_response=care_text) + + async def _aappend(tid: str, messages): + checkpoint.extend((tid, m.type, m.id, m.content) for m in messages) + return list(messages) + + agent.aappend_messages = AsyncMock(side_effect=_aappend) + gateway, agent_manager = _build_real_gateway(db, agent) + gateway.notify_dashboard_push = AsyncMock(return_value=None) + + session_key = ThreadRegistry.make_key( + agent_id=agent_id, + channel_type="weixin", + channel_subject_id="wx_u1", + channel_chat_type="dm", + ) + ThreadRepo(db).insert( + thread_id="thr_im", + agent_id=agent_id, + user_id=1, + channel_type="weixin", + session_key=session_key, + last_active=1_700_000_000, + ) + SessionRepo(db).upsert( + session_key=session_key, + agent_id=agent_id, + user_id=1, + channel_type="weixin", + chat_type="dm", + thread_id="thr_im", + channel_id="ch_wx_1", + ) + + msg_repo = ThreadMessageRepo(db) + service = ProactiveCareService( + gateway=gateway, + care_push_repo=care_push_repo, + agent_manager=agent_manager, + thread_message_repo=msg_repo, + ) + await service.run(agent_id, session_key) + + assert len(checkpoint) == 1 + assert checkpoint[0][0] == "thr_im" + assert checkpoint[0][1] == "ai" + rows, _ = msg_repo.page("thr_im", limit=10) + assert len(rows) == 1 + assert rows[0].role == "ai" + gateway.notify_dashboard_push.assert_not_awaited() + + +@pytest.mark.asyncio +async def test_locked_can_send_false_discards_without_persisting( + db: SqlitePool, + agent_id: str, + care_push_repo: CarePushRepo, +) -> None: + """A second can_send() check inside the session lock prevents race-condition pushes.""" + agent = _make_agent([_make_episode("ep_race")], llm_response="你好呀") + gateway, agent_manager = _build_real_gateway(db, agent) + session_key = ThreadRegistry.dashboard_key(agent_id=agent_id, user_id=1) + ThreadRepo(db).insert( + thread_id="thr_race", + agent_id=agent_id, + user_id=1, + channel_type=ThreadRegistry.CHANNEL_DASHBOARD, + session_key=session_key, + last_active=1_700_000_000, + ) + SessionRepo(db).upsert( + session_key=session_key, + agent_id=agent_id, + user_id=1, + channel_type=ThreadRegistry.CHANNEL_DASHBOARD, + chat_type="dm", + thread_id="thr_race", + ) + + # First check (outside lock) returns True; second check (inside lock) returns False. + checks = iter([True, False]) + service = ProactiveCareService( + gateway=gateway, + care_push_repo=care_push_repo, + agent_manager=agent_manager, + thread_message_repo=ThreadMessageRepo(db), + ) + await service.run(agent_id, session_key, can_send=lambda: next(checks)) + + agent.aappend_messages.assert_not_awaited() + gateway._channel_manager.push_text.assert_not_awaited() + assert care_push_repo.list_recent(agent_id) == [] diff --git a/tests/unit/proactive/test_scheduler.py b/tests/unit/proactive/test_scheduler.py index 81916d73c6..7c9e0193a3 100644 --- a/tests/unit/proactive/test_scheduler.py +++ b/tests/unit/proactive/test_scheduler.py @@ -26,9 +26,11 @@ from octop.infra.db.repos.users import UserRepo from octop.infra.proactive.scheduler import ( ProactiveCareScheduler, + backoff_interval_hours, compute_next_trigger, decide_send_timing, is_in_active_hours, + select_care_target_session, ) from octop.infra.utils.ulid import new_ulid @@ -614,3 +616,187 @@ async def test_suspend_skips_new_schedules( scheduler.ensure_scheduled(agent_id) await scheduler.start_all() assert scheduler._tasks == {} + + +# --------------------------------------------------------------------------- +# Target session filtering, backoff, human-only idle, and HITL deferral tests +# --------------------------------------------------------------------------- + + +def _make_session_row( + *, + session_key: str, + channel_type: str, + chat_type: str = "dm", + channel_id: str | None = None, + thread_id: str = "thr_1", +): + from octop.infra.db.repos.sessions import SessionRow + + return SessionRow( + id=1, + session_key=session_key, + agent_id="a1", + user_id=1, + channel_type=channel_type, + chat_type=chat_type, + thread_id=thread_id, + updated_at=100, + channel_subject_id="u1", + channel_chat_type=chat_type, + channel_id=channel_id, + ) + + +def test_select_care_target_skips_mcp_group_peer_and_cli() -> None: + mcp = _make_session_row( + session_key="a1:mcp:1:call-1", + channel_type="mcp", + chat_type="call-1", + channel_id="octop-agent-mcp", + ) + qq_group = _make_session_row( + session_key="a1:qq:g1:group", + channel_type="qq", + chat_type="group", + channel_id="ch_qq", + ) + peer = _make_session_row( + session_key="a1:dashboard:1:peer:room1", + channel_type="dashboard", + chat_type="peer:room1", + ) + cli = _make_session_row( + session_key="a1:cli:1:dm", + channel_type="cli", + chat_type="dm", + ) + dash = _make_session_row( + session_key="a1:dashboard:1:dm", + channel_type="dashboard", + chat_type="dm", + ) + im_dm = _make_session_row( + session_key="a1:weixin:wx1:dm", + channel_type="weixin", + chat_type="dm", + channel_id="ch_wx", + ) + + assert select_care_target_session([mcp, qq_group, peer, cli]) is None + assert select_care_target_session([mcp, qq_group, peer, dash]) is dash + assert select_care_target_session([mcp, qq_group, dash, im_dm]) is im_dm + + +def test_backoff_interval_hours_scales_with_unanswered_streak() -> None: + assert backoff_interval_hours(5, 24, 0) == (5, 24) + assert backoff_interval_hours(5, 24, 1) == (5, 24) + assert backoff_interval_hours(5, 24, 2) == (10, 48) + assert backoff_interval_hours(5, 24, 3) == (20, 96) + assert backoff_interval_hours(60, 100, 4) == (168, 168) + + +def test_timing_uses_real_human_activity_and_ignores_cron_and_slack_bug( + db: SqlitePool, + agent_id: str, + config_repo: ProactiveCareConfigRepo, +) -> None: + """A human reply 1 minute after a care push must still restart the 4h idle clock.""" + from octop.infra.db.repos.care_push import CarePushRepo + from octop.infra.db.repos.sessions import SessionRepo + from octop.infra.db.repos.thread_messages import ThreadMessageInput, ThreadMessageRepo + from octop.infra.db.repos.threads import ThreadRepo + + now = datetime(2026, 7, 1, 15, 0, tzinfo=UTC) + now_s = _unix(now) + thread_repo = ThreadRepo(db) + msg_repo = ThreadMessageRepo(db) + care_repo = CarePushRepo(db) + + thread_repo.insert( + thread_id="thr_idle", + agent_id=agent_id, + user_id=1, + channel_type="dashboard", + session_key=f"{agent_id}:dashboard:1:dm", + last_active=now_s - 60, + ) + # Old real human message (6h ago), plus a recent synthetic cron prompt (10m ago), + # plus a recent care AI message (5m ago) -> user is STILL idle! + msg_repo.append_if_ready( + "thr_idle", + [ + ThreadMessageInput( + message_id="u_old", + role="human", + message_json='{"type":"human","data":{"content":"old"}}', + created_at=now_s - 6 * 3600, + ), + ThreadMessageInput( + message_id="cron:01abc:human", + role="human", + message_json='{"type":"human","data":{"content":"cron"}}', + created_at=now_s - 600, + ), + ThreadMessageInput( + message_id="care:01abc:assistant", + role="ai", + message_json='{"type":"ai","data":{"content":"care"}}', + created_at=now_s - 300, + ), + ], + ) + care_repo.insert( + agent_id=agent_id, + session_key=f"{agent_id}:dashboard:1:dm", + episode_ids=["ep1"], + pushed_at=now_s - 300, + thread_id="thr_idle", + message_id="care:01abc:assistant", + ) + + scheduler = ProactiveCareScheduler( + care_service=AsyncMock(), + config_repo=config_repo, + session_repo=SessionRepo(db), + thread_repo=thread_repo, + thread_message_repo=msg_repo, + care_push_repo=care_repo, + ) + cfg = config_repo.get(agent_id) + assert scheduler._timing_decision(agent_id, cfg, "UTC", now).send is True + + # Now user replies 60s after the care push (within the old 5-minute slack window!). + msg_repo.append_if_ready( + "thr_idle", + [ + ThreadMessageInput( + message_id="u_quick_reply", + role="human", + message_json='{"type":"human","data":{"content":"thanks!"}}', + created_at=now_s - 240, + ), + ], + ) + decision = scheduler._timing_decision(agent_id, cfg, "UTC", now) + assert decision.send is False + assert decision.retry_at == datetime.fromtimestamp(now_s - 240, tz=UTC) + timedelta(hours=4) + + +def test_timing_defers_when_agent_has_pending_hitl( + db: SqlitePool, + agent_id: str, + config_repo: ProactiveCareConfigRepo, +) -> None: + from octop.infra.db.repos.sessions import SessionRepo + + now = datetime(2026, 7, 1, 15, 0, tzinfo=UTC) + scheduler = ProactiveCareScheduler( + care_service=AsyncMock(), + config_repo=config_repo, + session_repo=SessionRepo(db), + has_pending_hitl=lambda aid: aid == agent_id, + ) + decision = scheduler._timing_decision(agent_id, config_repo.get(agent_id), "UTC", now) + assert decision.send is False + assert decision.retry_at == now + timedelta(minutes=15)