fixed reminder

This commit is contained in:
2026-06-11 12:22:37 +03:00
parent 4108d737e3
commit 41cbef61a9
12 changed files with 410 additions and 59 deletions
+73
View File
@@ -0,0 +1,73 @@
import logging
from datetime import datetime, timezone
from sqlalchemy.orm import Session
from app.character.service import CharacterService
from app.chat.notice_inbox import post_character_comment_to_latest_chat, post_notice_to_latest_chat
from app.db.models import Reminder
from app.llm.client import LLMClient
from app.reminders.service import RECURRENCE_NONE, _advance_due, _format_local
logger = logging.getLogger(__name__)
def format_reminder_notice(row: Reminder) -> str:
local_when = _format_local(row.due_at, row.timezone, all_day=row.all_day)
notice = f"📅 **Напоминание** · {row.title}\n\n_{local_when}_"
if row.notes:
notice += f"\n{row.notes}"
return notice
class ReminderCompletionHandler:
def __init__(self, db: Session):
self.db = db
self.llm = LLMClient()
self.character = CharacterService()
async def _generate_llm_comment(self, row: Reminder, local_when: str) -> str:
notes_part = f"\nЗаметки: {row.notes}" if row.notes else ""
rec_part = ""
if row.recurrence and row.recurrence != RECURRENCE_NONE:
rec_part = f"\nПовтор: {row.recurrence}"
system = self.character.get_system_prompt()
user_prompt = f"""Сработало напоминание.
Заголовок: {row.title}
Время: {local_when}{notes_part}{rec_part}
Напиши пользователю короткое сообщение (2-4 предложения) на русском: напомни о деле, поддержи или предложи действие. Без markdown и без эмодзи."""
result = await self.llm.complete(
[
{"role": "system", "content": system},
{"role": "user", "content": user_prompt},
],
temperature=0.8,
visible_reply=True,
)
return (result.get("content") or "").strip() or f"Напоминание: {row.title}"
def _mark_fired(self, row: Reminder, now: datetime) -> None:
row.last_fired_at = now
if row.recurrence == RECURRENCE_NONE:
row.completed_at = now
row.enabled = False
else:
row.due_at = _advance_due(row.due_at, row.recurrence)
row.last_fired_at = None
row.updated_at = now
async def process(self, row: Reminder) -> None:
local_when = _format_local(row.due_at, row.timezone, all_day=row.all_day)
post_notice_to_latest_chat(format_reminder_notice(row))
try:
comment = await self._generate_llm_comment(row, local_when)
if comment:
post_character_comment_to_latest_chat(comment)
except Exception:
logger.exception("Reminder LLM comment failed (id=%s)", row.id)
self._mark_fired(row, datetime.now(timezone.utc))
+14 -29
View File
@@ -4,10 +4,9 @@ from datetime import datetime, timezone
from sqlalchemy import select
from sqlalchemy.orm import Session
from app.chat.notice_inbox import post_notice_to_latest_chat
from app.db.models import Reminder
from app.reminders.completion import ReminderCompletionHandler
from app.reminders.notify import bump_notify_seq
from app.reminders.service import RECURRENCE_NONE, _advance_due, _format_local
logger = logging.getLogger(__name__)
@@ -16,7 +15,7 @@ def _utcnow() -> datetime:
return datetime.now(timezone.utc)
def check_due_reminders(db: Session) -> int:
def get_due_reminders(db: Session) -> list[Reminder]:
now = _utcnow()
stmt = (
select(Reminder)
@@ -28,33 +27,19 @@ def check_due_reminders(db: Session) -> int:
.order_by(Reminder.due_at.asc())
)
rows = list(db.scalars(stmt).all())
fired = 0
return [row for row in rows if not (row.last_fired_at and row.last_fired_at >= row.due_at)]
for row in rows:
if row.last_fired_at and row.last_fired_at >= row.due_at:
continue
local_when = _format_local(row.due_at, row.timezone, all_day=row.all_day)
notice = f"📅 **Напоминание** · {row.title}\n\n_{local_when}_"
if row.notes:
notice += f"\n{row.notes}"
async def process_due_reminders(db: Session) -> int:
due = get_due_reminders(db)
if not due:
return 0
post_notice_to_latest_chat(notice)
row.last_fired_at = now
handler = ReminderCompletionHandler(db)
for row in due:
await handler.process(row)
if row.recurrence == RECURRENCE_NONE:
row.completed_at = now
row.enabled = False
else:
row.due_at = _advance_due(row.due_at, row.recurrence)
row.last_fired_at = None
row.updated_at = now
fired += 1
if fired:
db.commit()
bump_notify_seq(db)
logger.info("Reminders fired: %d", fired)
return fired
db.commit()
bump_notify_seq(db)
logger.info("Reminders fired: %d", len(due))
return len(due)
+2 -2
View File
@@ -3,7 +3,7 @@ import logging
from app.config import get_settings
from app.db.base import SessionLocal
from app.reminders.fire import check_due_reminders
from app.reminders.fire import process_due_reminders
logger = logging.getLogger(__name__)
@@ -26,6 +26,6 @@ async def reminders_watcher_loop() -> None:
async def _tick() -> None:
db = SessionLocal()
try:
check_due_reminders(db)
await process_due_reminders(db)
finally:
db.close()