Commit 22d1dfc9 by sunqi02

fix: address code review issues

- C1: Move user message add before agent.reply() in try/finally
  to prevent message loss on agent errors
- C2: Add try/except with rollback around DB commit in save_to_db()
- I3: Move json and Session imports to top level
- M3: Add index on updated_at column per design spec

Reviewed-by: Claude Opus 4.7
1 parent bceb69e7
......@@ -6,3 +6,10 @@ DATABASE_URL=sqlite:///./dev.db
USE_CONSOLE_IM=false
IM_BASE_URL=http://yjy.dev.glsx.com.cn/webim
IM_API_KEY=
# 数据库
DB_HOST=192.168.3.92
DB_PORT=3308
DB_NAME=ai_multi_agentic
DB_USER=biz_multi_agentic
DB_PASSWORD=JEIjHeLT
\ No newline at end of file
......@@ -7,8 +7,8 @@ class Session(Base):
__tablename__ = "ai_sessions"
session_id = Column(String, primary_key=True, index=True)
room_id = Column(String, nullable=False, default="")
room_id = Column(String, nullable=False, default="", index=True)
channel = Column(String, nullable=False, default="wechat_group")
conversation_history = Column(Text, nullable=False, default="[]")
created_at = Column(DateTime, server_default=func.now(), nullable=False)
updated_at = Column(DateTime, server_default=func.now(), onupdate=func.now(), nullable=False)
updated_at = Column(DateTime, server_default=func.now(), onupdate=func.now(), nullable=False, index=True)
from __future__ import annotations
import json
import logging
from dataclasses import dataclass
from datetime import datetime, timezone
from typing import Optional
from app.infrastructure.session_store import SessionStore
from app.model.session import Session
logger = logging.getLogger(__name__)
def _utcnow_iso() -> str:
......@@ -43,12 +48,10 @@ class ActiveSessionService:
# 2. 查 DB(冷恢复)
if self._db:
from app.model.session import Session
db_sess = self._db.query(Session).filter(
Session.session_id == session_id
).first()
if db_sess:
import json
payload = {
"session_id": db_sess.session_id,
"channel": db_sess.channel,
......@@ -98,28 +101,29 @@ class ActiveSessionService:
if not data:
return
import json
from app.model.session import Session
existing = self._db.query(Session).filter(
Session.session_id == session_id
).first()
try:
existing = self._db.query(Session).filter(
Session.session_id == session_id
).first()
if existing:
existing.room_id = data.get("room_id", "")
existing.channel = data.get("channel", "wechat_group")
existing.conversation_history = json.dumps(
data.get("conversation_history", []), ensure_ascii=False
)
else:
db_sess = Session(
session_id=session_id,
room_id=data.get("room_id", ""),
channel=data.get("channel", "wechat_group"),
conversation_history=json.dumps(
if existing:
existing.room_id = data.get("room_id", "")
existing.channel = data.get("channel", "wechat_group")
existing.conversation_history = json.dumps(
data.get("conversation_history", []), ensure_ascii=False
),
)
self._db.add(db_sess)
)
else:
db_sess = Session(
session_id=session_id,
room_id=data.get("room_id", ""),
channel=data.get("channel", "wechat_group"),
conversation_history=json.dumps(
data.get("conversation_history", []), ensure_ascii=False
),
)
self._db.add(db_sess)
self._db.commit()
self._db.commit()
except Exception:
self._db.rollback()
logger.exception("Failed to persist session %s to DB", session_id)
......@@ -368,15 +368,16 @@ class AgentHub:
effective_query = f"{user_query}\n\n[用户发送了一张图片: {file_url}]"
user_msg = Msg("user", effective_query, "user")
response_msg = await agent.reply(user_msg)
response_content = response_msg.get_text_content()
# Store messages via SessionMemory
# Store user message BEFORE agent call so it persists even on error
memory.add("user", user_query, agent_code="main")
memory.add("assistant", response_content, agent_code=target_agent)
# 持久化到 DB
self.session_service.save_to_db(session_id)
try:
response_msg = await agent.reply(user_msg)
response_content = response_msg.get_text_content()
memory.add("assistant", response_content, agent_code=target_agent)
finally:
# 持久化到 DB — always save what we have
self.session_service.save_to_db(session_id)
# Send via hook
await self.post_reply_hook.execute({
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!