mermaid_cli/session/
conversation.rs1use crate::models::{ChatMessage, MessageRole};
2use anyhow::Result;
3use chrono::{DateTime, Local};
4use serde::{Deserialize, Serialize};
5use std::collections::VecDeque;
6use std::fs;
7use std::path::{Path, PathBuf};
8
9#[derive(Debug, Clone, Serialize, Deserialize)]
11pub struct ConversationHistory {
12 pub id: String,
13 pub title: String,
14 pub messages: Vec<ChatMessage>,
15 pub model_name: String,
16 pub project_path: String,
17 pub created_at: DateTime<Local>,
18 pub updated_at: DateTime<Local>,
19 pub total_tokens: Option<usize>,
20 #[serde(default)]
22 pub input_history: VecDeque<String>,
23}
24
25impl ConversationHistory {
26 pub fn new(project_path: String, model_name: String) -> Self {
28 let now = Local::now();
29 let id = format!("{}", now.format("%Y%m%d_%H%M%S_%3f"));
31 Self {
32 id: id.clone(),
33 title: format!("Session {}", now.format("%Y-%m-%d %H:%M")),
34 messages: Vec::new(),
35 model_name,
36 project_path,
37 created_at: now,
38 updated_at: now,
39 total_tokens: None,
40 input_history: VecDeque::new(),
41 }
42 }
43
44 pub fn add_messages(&mut self, messages: &[ChatMessage]) {
46 self.messages.extend_from_slice(messages);
47 self.updated_at = Local::now();
48 self.update_title();
49 }
50
51 pub fn add_to_input_history(&mut self, input: String) {
53 if input.trim().is_empty() {
55 return;
56 }
57
58 if let Some(last) = self.input_history.back()
60 && last == &input
61 {
62 return;
63 }
64
65 if self.input_history.len() >= 100 {
67 self.input_history.pop_front(); }
69
70 self.input_history.push_back(input);
71 }
72
73 fn update_title(&mut self) {
76 if !self.title.starts_with("Session ") {
78 return;
79 }
80 if let Some(first_user_msg) = self.messages.iter().find(|m| m.role == MessageRole::User) {
81 let preview = if first_user_msg.content.len() > 60 {
82 let end = first_user_msg.content.floor_char_boundary(60);
83 format!("{}...", &first_user_msg.content[..end])
84 } else {
85 first_user_msg.content.clone()
86 };
87 self.title = preview;
88 }
89 }
90
91 pub fn summary(&self) -> String {
93 let message_count = self.messages.len();
94 let duration = self.updated_at.signed_duration_since(self.created_at);
95 let hours = duration.num_hours();
96 let minutes = duration.num_minutes() % 60;
97
98 format!(
99 "{} | {} messages | {}h {}m | {}",
100 self.updated_at.format("%Y-%m-%d %H:%M"),
101 message_count,
102 hours,
103 minutes,
104 self.title
105 )
106 }
107}
108
109#[derive(Clone)]
111pub struct ConversationManager {
112 conversations_dir: PathBuf,
113}
114
115impl ConversationManager {
116 pub fn new(project_dir: impl AsRef<Path>) -> Result<Self> {
118 let conversations_dir = project_dir.as_ref().join(".mermaid").join("conversations");
119
120 fs::create_dir_all(&conversations_dir)?;
122
123 Ok(Self { conversations_dir })
124 }
125
126 pub fn save_conversation(&self, conversation: &ConversationHistory) -> Result<()> {
128 let filename = format!("{}.json", conversation.id);
129 let path = self.conversations_dir.join(filename);
130
131 let json = serde_json::to_string_pretty(conversation)?;
132 fs::write(path, json)?;
133
134 Ok(())
135 }
136
137 pub fn load_conversation(&self, id: &str) -> Result<ConversationHistory> {
139 let filename = format!("{}.json", id);
140 let path = self.conversations_dir.join(filename);
141
142 let json = fs::read_to_string(path)?;
143 let conversation: ConversationHistory = serde_json::from_str(&json)?;
144
145 Ok(conversation)
146 }
147
148 pub fn load_last_conversation(&self) -> Result<Option<ConversationHistory>> {
150 let conversations = self.list_conversations()?;
151
152 if conversations.is_empty() {
153 return Ok(None);
154 }
155
156 Ok(conversations.into_iter().next())
158 }
159
160 pub fn list_conversations(&self) -> Result<Vec<ConversationHistory>> {
162 let mut conversations = Vec::new();
163
164 if let Ok(entries) = fs::read_dir(&self.conversations_dir) {
166 for entry in entries.flatten() {
167 if let Some(ext) = entry.path().extension()
168 && ext == "json"
169 && let Ok(json) = fs::read_to_string(entry.path())
170 && let Ok(conv) = serde_json::from_str::<ConversationHistory>(&json)
171 {
172 conversations.push(conv);
173 }
174 }
175 }
176
177 conversations.sort_by(|a, b| b.updated_at.cmp(&a.updated_at));
179
180 Ok(conversations)
181 }
182
183 pub fn delete_conversation(&self, id: &str) -> Result<()> {
185 let filename = format!("{}.json", id);
186 let path = self.conversations_dir.join(filename);
187
188 if path.exists() {
189 fs::remove_file(path)?;
190 }
191
192 Ok(())
193 }
194
195 pub fn conversations_dir(&self) -> &Path {
197 &self.conversations_dir
198 }
199}