Skip to main content

mermaid_cli/session/
conversation.rs

1use 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/// A complete conversation history
10#[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    /// History of user input prompts for navigation (up/down arrows)
21    #[serde(default)]
22    pub input_history: VecDeque<String>,
23}
24
25impl ConversationHistory {
26    /// Create a new conversation history
27    pub fn new(project_path: String, model_name: String) -> Self {
28        let now = Local::now();
29        // Include subsecond precision to avoid ID collisions within the same second
30        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    /// Add messages to the conversation
45    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    /// Add input to history (with deduplication of consecutive identical inputs)
52    pub fn add_to_input_history(&mut self, input: String) {
53        // Skip empty inputs
54        if input.trim().is_empty() {
55            return;
56        }
57
58        // Don't add if it's identical to the last entry
59        if let Some(last) = self.input_history.back()
60            && last == &input
61        {
62            return;
63        }
64
65        // Cap history at 100 entries to prevent unbounded growth
66        if self.input_history.len() >= 100 {
67            self.input_history.pop_front(); // O(1) instead of O(n)
68        }
69
70        self.input_history.push_back(input);
71    }
72
73    /// Update the title based on the first user message.
74    /// Short-circuits if the title was already derived from a user message.
75    fn update_title(&mut self) {
76        // Only set title once — it comes from the first user message
77        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    /// Get a summary for display
92    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/// Manages conversation persistence for a project
110#[derive(Clone)]
111pub struct ConversationManager {
112    conversations_dir: PathBuf,
113}
114
115impl ConversationManager {
116    /// Create a new conversation manager for a project directory
117    pub fn new(project_dir: impl AsRef<Path>) -> Result<Self> {
118        let conversations_dir = project_dir.as_ref().join(".mermaid").join("conversations");
119
120        // Create conversations directory if it doesn't exist
121        fs::create_dir_all(&conversations_dir)?;
122
123        Ok(Self { conversations_dir })
124    }
125
126    /// Save a conversation to disk
127    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    /// Load a specific conversation by ID
138    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    /// Load the most recent conversation
149    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        // Conversations are already sorted by modification time (newest first)
157        Ok(conversations.into_iter().next())
158    }
159
160    /// List all conversations in the project
161    pub fn list_conversations(&self) -> Result<Vec<ConversationHistory>> {
162        let mut conversations = Vec::new();
163
164        // Read all JSON files in the conversations directory
165        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        // Sort by updated_at (newest first)
178        conversations.sort_by(|a, b| b.updated_at.cmp(&a.updated_at));
179
180        Ok(conversations)
181    }
182
183    /// Delete a conversation
184    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    /// Get the conversations directory path
196    pub fn conversations_dir(&self) -> &Path {
197        &self.conversations_dir
198    }
199}
200
201#[cfg(test)]
202mod tests {
203    use super::*;
204
205    #[test]
206    fn test_new_conversation_has_session_title() {
207        let conv = ConversationHistory::new("/tmp/project".into(), "test-model".into());
208        assert!(conv.title.starts_with("Session "));
209        assert_eq!(conv.model_name, "test-model");
210        assert_eq!(conv.project_path, "/tmp/project");
211        assert!(conv.messages.is_empty());
212    }
213
214    #[test]
215    fn test_title_updates_from_first_user_message() {
216        let mut conv = ConversationHistory::new("/tmp".into(), "m".into());
217        conv.add_messages(&[ChatMessage::user("Fix the login bug")]);
218        assert_eq!(conv.title, "Fix the login bug");
219    }
220
221    #[test]
222    fn test_title_truncated_at_60_chars() {
223        let mut conv = ConversationHistory::new("/tmp".into(), "m".into());
224        let long_msg = "a".repeat(100);
225        conv.add_messages(&[ChatMessage::user(long_msg)]);
226        assert!(conv.title.ends_with("..."));
227        assert!(conv.title.len() <= 64); // 60 chars + "..."
228    }
229
230    #[test]
231    fn test_title_set_only_once() {
232        let mut conv = ConversationHistory::new("/tmp".into(), "m".into());
233        conv.add_messages(&[ChatMessage::user("First message")]);
234        conv.add_messages(&[ChatMessage::user("Second message")]);
235        assert_eq!(conv.title, "First message");
236    }
237
238    #[test]
239    fn test_input_history_deduplication() {
240        let mut conv = ConversationHistory::new("/tmp".into(), "m".into());
241        conv.add_to_input_history("hello".into());
242        conv.add_to_input_history("hello".into()); // duplicate
243        conv.add_to_input_history("world".into());
244        assert_eq!(conv.input_history.len(), 2);
245    }
246
247    #[test]
248    fn test_input_history_skips_empty() {
249        let mut conv = ConversationHistory::new("/tmp".into(), "m".into());
250        conv.add_to_input_history("".into());
251        conv.add_to_input_history("   ".into());
252        assert_eq!(conv.input_history.len(), 0);
253    }
254
255    #[test]
256    fn test_input_history_capped_at_100() {
257        let mut conv = ConversationHistory::new("/tmp".into(), "m".into());
258        for i in 0..110 {
259            conv.add_to_input_history(format!("msg{}", i));
260        }
261        assert_eq!(conv.input_history.len(), 100);
262        assert_eq!(conv.input_history.front().unwrap(), "msg10");
263    }
264
265    #[test]
266    fn test_save_load_roundtrip() {
267        let dir = std::env::temp_dir().join("mermaid_test_conv_roundtrip");
268        let _ = fs::remove_dir_all(&dir);
269        let manager = ConversationManager::new(&dir).unwrap();
270
271        let mut conv = ConversationHistory::new("/tmp".into(), "model".into());
272        conv.add_messages(&[ChatMessage::user("test message")]);
273        conv.add_to_input_history("test message".into());
274
275        manager.save_conversation(&conv).unwrap();
276        let loaded = manager.load_conversation(&conv.id).unwrap();
277
278        assert_eq!(loaded.id, conv.id);
279        assert_eq!(loaded.title, conv.title);
280        assert_eq!(loaded.messages.len(), 1);
281        assert_eq!(loaded.input_history.len(), 1);
282
283        let _ = fs::remove_dir_all(&dir);
284    }
285
286    #[test]
287    fn test_list_conversations_ordered_by_updated_at() {
288        let dir = std::env::temp_dir().join("mermaid_test_conv_list");
289        let _ = fs::remove_dir_all(&dir);
290        let manager = ConversationManager::new(&dir).unwrap();
291
292        let conv1 = ConversationHistory::new("/tmp".into(), "m".into());
293        std::thread::sleep(std::time::Duration::from_millis(10));
294        let conv2 = ConversationHistory::new("/tmp".into(), "m".into());
295
296        manager.save_conversation(&conv1).unwrap();
297        manager.save_conversation(&conv2).unwrap();
298
299        let list = manager.list_conversations().unwrap();
300        assert_eq!(list.len(), 2);
301        // Newest first
302        assert_eq!(list[0].id, conv2.id);
303        assert_eq!(list[1].id, conv1.id);
304
305        let _ = fs::remove_dir_all(&dir);
306    }
307
308    #[test]
309    fn test_load_last_conversation() {
310        let dir = std::env::temp_dir().join("mermaid_test_conv_last");
311        let _ = fs::remove_dir_all(&dir);
312        let manager = ConversationManager::new(&dir).unwrap();
313
314        assert!(manager.load_last_conversation().unwrap().is_none());
315
316        let conv = ConversationHistory::new("/tmp".into(), "m".into());
317        manager.save_conversation(&conv).unwrap();
318
319        let last = manager.load_last_conversation().unwrap().unwrap();
320        assert_eq!(last.id, conv.id);
321
322        let _ = fs::remove_dir_all(&dir);
323    }
324
325    #[test]
326    fn test_delete_conversation() {
327        let dir = std::env::temp_dir().join("mermaid_test_conv_delete");
328        let _ = fs::remove_dir_all(&dir);
329        let manager = ConversationManager::new(&dir).unwrap();
330
331        let conv = ConversationHistory::new("/tmp".into(), "m".into());
332        manager.save_conversation(&conv).unwrap();
333        assert_eq!(manager.list_conversations().unwrap().len(), 1);
334
335        manager.delete_conversation(&conv.id).unwrap();
336        assert_eq!(manager.list_conversations().unwrap().len(), 0);
337
338        let _ = fs::remove_dir_all(&dir);
339    }
340}