feat: 自动从数据库恢复当前话题,增强会话管理功能

This commit is contained in:
ooodc 2026-05-16 20:45:28 +08:00
parent 6a902b9ff9
commit 428df8da59

View File

@ -547,11 +547,30 @@ impl SessionManager {
self.lifecycle.get(channel_name).await self.lifecycle.get(channel_name).await
} }
/// 获取指定 chat 的当前话题(确保 session 存在 /// 获取指定 chat 的当前话题(确保 session 存在,自动从数据库恢复
pub async fn get_current_topic(&self, channel_name: &str, chat_id: &str) -> Result<Option<String>, AgentError> { pub async fn get_current_topic(&self, channel_name: &str, chat_id: &str) -> Result<Option<String>, AgentError> {
self.ensure_session(channel_name).await?; self.ensure_session(channel_name).await?;
if let Some(session) = self.get(channel_name).await { if let Some(session) = self.get(channel_name).await {
let guard = session.lock().await; let mut guard = session.lock().await;
// 如果内存中没有当前话题,从数据库恢复最近活跃的话题
if guard.current_topic(chat_id).is_none() {
let session_id = guard.persistent_session_id(chat_id);
let topics = self.store.list_topics(&session_id)
.map_err(|e| AgentError::Other(format!("Failed to list topics: {}", e)))?;
if let Some(latest_topic) = topics.first() {
// 设置最近活跃的话题为当前话题
guard.set_current_topic(chat_id, Some(latest_topic.id.clone()));
tracing::info!(
chat_id = %chat_id,
topic_id = %latest_topic.id,
topic_title = %latest_topic.title,
"Restored current topic from database"
);
}
}
Ok(guard.current_topic(chat_id).map(|s| s.to_string())) Ok(guard.current_topic(chat_id).map(|s| s.to_string()))
} else { } else {
Ok(None) Ok(None)