Skip to content

Commit a4a8dd4

Browse files
Bosheng0422Test
andauthored
fix(proactive): persist care messages to thread history and track replies (#3133)
Fixes #3064 Co-authored-by: Test <test@example.com>
1 parent 8837629 commit a4a8dd4

12 files changed

Lines changed: 1216 additions & 43 deletions

File tree

‎src/octop/infra/db/migrate.py‎

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1821,6 +1821,39 @@ def _ensure_thread_contributed_schema(db: DatabasePool) -> None:
18211821
_ensure_column(db, "threads", "contributed", "INTEGER NOT NULL DEFAULT 0")
18221822

18231823

1824+
def _ensure_care_push_reply_schema(db: DatabasePool) -> None:
1825+
"""Proactive care thread/message/reply tracking on ``care_push_records``. Idempotent."""
1826+
if not _table_exists(db, "care_push_records"):
1827+
return
1828+
ts_type = "BIGINT" if db.dialect == "postgresql" else "INTEGER"
1829+
_ensure_column(db, "care_push_records", "thread_id", "TEXT")
1830+
_ensure_column(db, "care_push_records", "message_id", "TEXT")
1831+
_ensure_column(db, "care_push_records", "care_text", "TEXT")
1832+
_ensure_column(db, "care_push_records", "status", "TEXT NOT NULL DEFAULT 'sent'")
1833+
_ensure_column(db, "care_push_records", "replied_at", ts_type)
1834+
_ensure_column(db, "care_push_records", "reply_message_id", "TEXT")
1835+
if db.dialect == "postgresql":
1836+
with db.connect() as conn, conn.transaction():
1837+
conn.execute(
1838+
"CREATE INDEX IF NOT EXISTS idx_care_push_thread_status "
1839+
"ON care_push_records(thread_id, status, pushed_at)"
1840+
)
1841+
conn.execute(
1842+
"CREATE INDEX IF NOT EXISTS idx_care_push_agent_status "
1843+
"ON care_push_records(agent_id, status, pushed_at)"
1844+
)
1845+
return
1846+
with db.transaction() as conn:
1847+
conn.execute(
1848+
"CREATE INDEX IF NOT EXISTS idx_care_push_thread_status "
1849+
"ON care_push_records(thread_id, status, pushed_at)"
1850+
)
1851+
conn.execute(
1852+
"CREATE INDEX IF NOT EXISTS idx_care_push_agent_status "
1853+
"ON care_push_records(agent_id, status, pushed_at)"
1854+
)
1855+
1856+
18241857
_LOGIN_AUDIT_ACTIONS_SQL = (
18251858
"'auth.login', 'auth.ldap_login', 'auth.oidc_login', 'auth.passkey_login'"
18261859
)
@@ -2805,6 +2838,7 @@ def run_migrations(db: DatabasePool) -> None:
28052838
_ensure_instance_lease_schema(db)
28062839
_ensure_control_blobs_schema(db)
28072840
_ensure_thread_contributed_schema(db)
2841+
_ensure_care_push_reply_schema(db)
28082842
_ensure_invite_redemptions_schema(db)
28092843
_grant_default_nav_permissions(db)
28102844
_grant_personalization_tab_permissions(db)

‎src/octop/infra/db/repos/care_push.py‎

Lines changed: 173 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,52 @@
11
"""Data-access layer for the proactive care push records table.
22
33
The care_push_records table records the episode_id consumed by each proactive_care
4-
push, used to avoid re-pushing the same event within 30 days.
4+
push (used for 30-day dedup) along with delivery coordinates (thread_id, message_id)
5+
and user reply status for backoff and downstream memory feedback.
56
"""
67

78
from __future__ import annotations
89

910
import time
1011
import uuid
1112
from collections.abc import Sequence
13+
from dataclasses import dataclass
1214

1315
from octop.infra.db.pool import DatabasePool
16+
from octop.infra.db.repos._base import DbRow
17+
18+
19+
@dataclass(frozen=True)
20+
class CarePushRecord:
21+
"""One row from ``care_push_records``."""
22+
23+
id: str
24+
agent_id: str
25+
session_key: str
26+
episode_id: str
27+
pushed_at: int
28+
thread_id: str | None = None
29+
message_id: str | None = None
30+
care_text: str | None = None
31+
status: str = "sent"
32+
replied_at: int | None = None
33+
reply_message_id: str | None = None
34+
35+
@classmethod
36+
def from_row(cls, row: DbRow) -> CarePushRecord:
37+
return cls(
38+
id=str(row["id"]),
39+
agent_id=str(row["agent_id"]),
40+
session_key=str(row["session_key"]),
41+
episode_id=str(row["episode_id"]),
42+
pushed_at=int(row["pushed_at"]),
43+
thread_id=str(row["thread_id"]) if row["thread_id"] else None,
44+
message_id=str(row["message_id"]) if row["message_id"] else None,
45+
care_text=str(row["care_text"]) if row["care_text"] is not None else None,
46+
status=str(row["status"] or "sent"),
47+
replied_at=int(row["replied_at"]) if row["replied_at"] is not None else None,
48+
reply_message_id=str(row["reply_message_id"]) if row["reply_message_id"] else None,
49+
)
1450

1551

1652
class CarePushRepo:
@@ -26,26 +62,158 @@ def insert(
2662
session_key: str,
2763
episode_ids: Sequence[str],
2864
pushed_at: int | None = None,
65+
thread_id: str | None = None,
66+
message_id: str | None = None,
67+
care_text: str | None = None,
2968
) -> None:
30-
"""Batch-insert push records.
69+
"""Batch-insert push records for one proactive care delivery.
3170
3271
Args:
3372
agent_id: The agent ID the push belongs to.
3473
session_key: The session key the push belongs to.
3574
episode_ids: The list of episode IDs consumed by this push.
3675
pushed_at: Push timestamp (unix); defaults to the current time.
76+
thread_id: Target thread ID where the care message was stored.
77+
message_id: Canonical ``AIMessage.id`` stored in the thread.
78+
care_text: Delivered care text (for reply correlation and feedback).
3779
"""
3880
if not episode_ids:
3981
return
4082
ts = pushed_at if pushed_at is not None else int(time.time())
41-
rows = [(str(uuid.uuid4()), agent_id, session_key, ep_id, ts) for ep_id in episode_ids]
83+
rows = [
84+
(
85+
str(uuid.uuid4()),
86+
agent_id,
87+
session_key,
88+
ep_id,
89+
ts,
90+
thread_id,
91+
message_id,
92+
care_text,
93+
"sent",
94+
)
95+
for ep_id in episode_ids
96+
]
4297
with self._db.transaction() as conn:
4398
conn.executemany(
44-
"INSERT INTO care_push_records(id, agent_id, session_key, episode_id, pushed_at) "
45-
"VALUES (?, ?, ?, ?, ?)",
99+
"INSERT INTO care_push_records("
100+
"id, agent_id, session_key, episode_id, pushed_at, "
101+
"thread_id, message_id, care_text, status"
102+
") VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)",
46103
rows,
47104
)
48105

106+
def mark_replied_for_thread(
107+
self,
108+
*,
109+
agent_id: str,
110+
thread_id: str,
111+
reply_message_id: str | None = None,
112+
replied_at: int | None = None,
113+
) -> int:
114+
"""Record that the user replied in *thread_id* after a proactive care push.
115+
116+
The latest open (``status='sent'``) care push in *thread_id* is marked
117+
``'replied'``; any older still-open pushes in the same thread are marked
118+
``'ignored'`` so reply attribution stays tied to the message the user saw.
119+
120+
Returns:
121+
Number of rows marked ``'replied'``.
122+
"""
123+
tid = thread_id.strip()
124+
if not tid:
125+
return 0
126+
ts = replied_at if replied_at is not None else int(time.time())
127+
with self._db.transaction() as conn:
128+
latest = conn.execute(
129+
"SELECT message_id, pushed_at FROM care_push_records "
130+
"WHERE agent_id = ? AND thread_id = ? AND status = 'sent' AND pushed_at <= ? "
131+
"ORDER BY pushed_at DESC LIMIT 1",
132+
(agent_id, tid, ts),
133+
).fetchone()
134+
if latest is None:
135+
return 0
136+
latest_mid = latest["message_id"]
137+
latest_pushed_at = int(latest["pushed_at"])
138+
if latest_mid:
139+
cur = conn.execute(
140+
"UPDATE care_push_records "
141+
"SET status = 'replied', replied_at = ?, reply_message_id = ? "
142+
"WHERE agent_id = ? AND thread_id = ? AND status = 'sent' "
143+
"AND message_id = ?",
144+
(ts, reply_message_id, agent_id, tid, latest_mid),
145+
)
146+
replied_count = int(cur.rowcount or 0)
147+
conn.execute(
148+
"UPDATE care_push_records "
149+
"SET status = 'ignored' "
150+
"WHERE agent_id = ? AND thread_id = ? AND status = 'sent' "
151+
"AND pushed_at <= ? AND (message_id IS NULL OR message_id <> ?)",
152+
(agent_id, tid, ts, latest_mid),
153+
)
154+
else:
155+
cur = conn.execute(
156+
"UPDATE care_push_records "
157+
"SET status = 'replied', replied_at = ?, reply_message_id = ? "
158+
"WHERE agent_id = ? AND thread_id = ? AND status = 'sent' "
159+
"AND pushed_at = ?",
160+
(ts, reply_message_id, agent_id, tid, latest_pushed_at),
161+
)
162+
replied_count = int(cur.rowcount or 0)
163+
conn.execute(
164+
"UPDATE care_push_records "
165+
"SET status = 'ignored' "
166+
"WHERE agent_id = ? AND thread_id = ? AND status = 'sent' "
167+
"AND pushed_at < ?",
168+
(agent_id, tid, latest_pushed_at),
169+
)
170+
return replied_count
171+
172+
def count_consecutive_unanswered(self, agent_id: str, *, limit: int = 20) -> int:
173+
"""Count consecutive recent care pushes for *agent_id* without a reply.
174+
175+
Multiple episode rows emitted by the same delivery (sharing ``message_id``,
176+
or ``(pushed_at, session_key)`` for legacy rows) are collapsed into one push.
177+
"""
178+
with self._db.connect() as conn:
179+
rows = conn.execute(
180+
"SELECT message_id, pushed_at, session_key, status "
181+
"FROM care_push_records "
182+
"WHERE agent_id = ? "
183+
"ORDER BY pushed_at DESC LIMIT ?",
184+
(agent_id, max(limit * 3, 30)),
185+
).fetchall()
186+
seen_keys: list[tuple[str, int, str]] = []
187+
push_replied: dict[tuple[str, int, str], bool] = {}
188+
for row in rows:
189+
mid = str(row["message_id"] or "")
190+
key = (mid, int(row["pushed_at"]), str(row["session_key"])) if not mid else (mid, 0, "")
191+
if key not in push_replied:
192+
if len(seen_keys) >= limit:
193+
break
194+
seen_keys.append(key)
195+
push_replied[key] = False
196+
if str(row["status"] or "sent") == "replied":
197+
push_replied[key] = True
198+
streak = 0
199+
for key in seen_keys:
200+
if push_replied[key]:
201+
break
202+
streak += 1
203+
return streak
204+
205+
def list_recent(self, agent_id: str, *, limit: int = 20) -> list[CarePushRecord]:
206+
"""Return the most recent care push rows for *agent_id*."""
207+
with self._db.connect() as conn:
208+
rows = conn.execute(
209+
"SELECT id, agent_id, session_key, episode_id, pushed_at, "
210+
"thread_id, message_id, care_text, status, replied_at, reply_message_id "
211+
"FROM care_push_records WHERE agent_id = ? "
212+
"ORDER BY pushed_at DESC LIMIT ?",
213+
(agent_id, limit),
214+
).fetchall()
215+
return [CarePushRecord.from_row(r) for r in rows]
216+
49217
def latest_pushed_at(self, agent_id: str) -> int | None:
50218
"""Unix time of the most recent care push for ``agent_id``, if any."""
51219
with self._db.connect() as conn:

‎src/octop/infra/db/repos/thread_messages.py‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,27 @@ def head(self, thread_id: str) -> int:
6767
).fetchone()
6868
return int(row[0])
6969

70+
def latest_human_activity(self, agent_id: str) -> int | None:
71+
"""Latest real human message timestamp (unix seconds) for *agent_id*.
72+
73+
Excludes synthetic cron prompts (``cron:%``) so scheduled runs and
74+
proactive care messages do not distort the user-idle clock.
75+
"""
76+
with self._db.connect() as conn:
77+
row = conn.execute(
78+
"SELECT MAX(tm.created_at) "
79+
"FROM thread_messages tm "
80+
"JOIN threads t ON t.thread_id = tm.thread_id "
81+
"WHERE t.agent_id = ? "
82+
"AND tm.role IN ('human', 'user') "
83+
"AND (tm.message_id IS NULL OR tm.message_id NOT LIKE 'cron:%')",
84+
(agent_id,),
85+
).fetchone()
86+
if row is None or row[0] is None:
87+
return None
88+
ts = int(row[0])
89+
return ts if ts > 0 else None
90+
7091
def threads_with_messages(self, thread_ids: Sequence[str]) -> set[str]:
7192
"""Which of *thread_ids* actually have projected messages.
7293

‎src/octop/infra/gateway/gateway.py‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -152,6 +152,7 @@ def replace_repos(self, repos: RepoBundle) -> None:
152152
)
153153
if self._processor is not None:
154154
self._processor.replace_thread_message_repo(repos.thread_message_repo)
155+
self._processor.replace_care_push_repo(repos.care_push_repo)
155156
self._processor.hitl_coordinator.session_policies.replace_repo(repos.thread_repo)
156157

157158
@property
@@ -286,6 +287,7 @@ async def boot(self, *, serve_background: bool = True) -> None:
286287
dispatcher=self._dispatcher,
287288
usage_repo=self._repos.usage_repo,
288289
thread_message_repo=self._repos.thread_message_repo,
290+
care_push_repo=self._repos.care_push_repo,
289291
gateway=self,
290292
trajectory_service=self._trajectory_service,
291293
)

‎src/octop/infra/gateway/hitl/store.py‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -295,6 +295,19 @@ def pending_thread_ids(
295295
out.add(tid)
296296
return frozenset(out)
297297

298+
def has_pending_for_agent(self, agent_id: str) -> bool:
299+
"""Whether *agent_id* has any live pending HITL pause across all users."""
300+
self._gc()
301+
now = time.time()
302+
for record in self._records.values():
303+
if record.status != "pending":
304+
continue
305+
if now - record.created_at > self.ttl_seconds:
306+
continue
307+
if record.agent_id == agent_id or record.resume_agent_id == agent_id:
308+
return True
309+
return False
310+
298311
def expire_pending_for_thread(
299312
self,
300313
thread_id: str,

0 commit comments

Comments
 (0)