use crate::models::{ChatMessage, MessageRole};
use anyhow::Result;
use chrono::{DateTime, Local};
use serde::{Deserialize, Serialize};
use std::collections::VecDeque;
use std::fs;
use std::path::{Path, PathBuf};
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ConversationHistory {
pub id: String,
pub title: String,
pub messages: Vec<ChatMessage>,
pub model_name: String,
pub project_path: String,
pub created_at: DateTime<Local>,
pub updated_at: DateTime<Local>,
pub total_tokens: Option<usize>,
#[serde(default)]
pub input_history: VecDeque<String>,
}
impl ConversationHistory {
pub fn new(project_path: String, model_name: String) -> Self {
let now = Local::now();
let id = format!("{}", now.format("%Y%m%d_%H%M%S"));
Self {
id: id.clone(),
title: format!("Session {}", now.format("%Y-%m-%d %H:%M")),
messages: Vec::new(),
model_name,
project_path,
created_at: now,
updated_at: now,
total_tokens: None,
input_history: VecDeque::new(),
}
}
pub fn add_messages(&mut self, messages: &[ChatMessage]) {
self.messages.extend_from_slice(messages);
self.updated_at = Local::now();
self.update_title();
}
pub fn add_to_input_history(&mut self, input: String) {
if input.trim().is_empty() {
return;
}
if let Some(last) = self.input_history.back() {
if last == &input {
return;
}
}
if self.input_history.len() >= 100 {
self.input_history.pop_front(); }
self.input_history.push_back(input);
}
fn update_title(&mut self) {
if let Some(first_user_msg) = self.messages.iter().find(|m| m.role == MessageRole::User) {
let preview = if first_user_msg.content.len() > 60 {
let end = first_user_msg.content.floor_char_boundary(60);
format!("{}...", &first_user_msg.content[..end])
} else {
first_user_msg.content.clone()
};
self.title = preview;
}
}
pub fn summary(&self) -> String {
let message_count = self.messages.len();
let duration = self.updated_at.signed_duration_since(self.created_at);
let hours = duration.num_hours();
let minutes = duration.num_minutes() % 60;
format!(
"{} | {} messages | {}h {}m | {}",
self.updated_at.format("%Y-%m-%d %H:%M"),
message_count,
hours,
minutes,
self.title
)
}
}
pub struct ConversationManager {
conversations_dir: PathBuf,
}
impl ConversationManager {
pub fn new(project_dir: impl AsRef<Path>) -> Result<Self> {
let conversations_dir = project_dir.as_ref().join(".mermaid").join("conversations");
fs::create_dir_all(&conversations_dir)?;
Ok(Self { conversations_dir })
}
pub fn save_conversation(&self, conversation: &ConversationHistory) -> Result<()> {
let filename = format!("{}.json", conversation.id);
let path = self.conversations_dir.join(filename);
let json = serde_json::to_string_pretty(conversation)?;
fs::write(path, json)?;
Ok(())
}
pub fn load_conversation(&self, id: &str) -> Result<ConversationHistory> {
let filename = format!("{}.json", id);
let path = self.conversations_dir.join(filename);
let json = fs::read_to_string(path)?;
let conversation: ConversationHistory = serde_json::from_str(&json)?;
Ok(conversation)
}
pub fn load_last_conversation(&self) -> Result<Option<ConversationHistory>> {
let conversations = self.list_conversations()?;
if conversations.is_empty() {
return Ok(None);
}
Ok(conversations.into_iter().next())
}
pub fn list_conversations(&self) -> Result<Vec<ConversationHistory>> {
let mut conversations = Vec::new();
if let Ok(entries) = fs::read_dir(&self.conversations_dir) {
for entry in entries.flatten() {
if let Some(ext) = entry.path().extension() {
if ext == "json" {
if let Ok(json) = fs::read_to_string(entry.path()) {
if let Ok(conv) = serde_json::from_str::<ConversationHistory>(&json) {
conversations.push(conv);
}
}
}
}
}
}
conversations.sort_by(|a, b| b.updated_at.cmp(&a.updated_at));
Ok(conversations)
}
pub fn delete_conversation(&self, id: &str) -> Result<()> {
let filename = format!("{}.json", id);
let path = self.conversations_dir.join(filename);
if path.exists() {
fs::remove_file(path)?;
}
Ok(())
}
pub fn conversations_dir(&self) -> &Path {
&self.conversations_dir
}
}