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                return;
62            }
63
64        // Cap history at 100 entries to prevent unbounded growth
65        if self.input_history.len() >= 100 {
66            self.input_history.pop_front(); // O(1) instead of O(n)
67        }
68
69        self.input_history.push_back(input);
70    }
71
72    /// Update the title based on the first user message
73    fn update_title(&mut self) {
74        if let Some(first_user_msg) = self.messages.iter().find(|m| m.role == MessageRole::User) {
75            // Take first 60 chars of first user message as title
76            let preview = if first_user_msg.content.len() > 60 {
77                let end = first_user_msg.content.floor_char_boundary(60);
78                format!("{}...", &first_user_msg.content[..end])
79            } else {
80                first_user_msg.content.clone()
81            };
82            self.title = preview;
83        }
84    }
85
86    /// Get a summary for display
87    pub fn summary(&self) -> String {
88        let message_count = self.messages.len();
89        let duration = self.updated_at.signed_duration_since(self.created_at);
90        let hours = duration.num_hours();
91        let minutes = duration.num_minutes() % 60;
92
93        format!(
94            "{} | {} messages | {}h {}m | {}",
95            self.updated_at.format("%Y-%m-%d %H:%M"),
96            message_count,
97            hours,
98            minutes,
99            self.title
100        )
101    }
102}
103
104/// Manages conversation persistence for a project
105pub struct ConversationManager {
106    conversations_dir: PathBuf,
107}
108
109impl ConversationManager {
110    /// Create a new conversation manager for a project directory
111    pub fn new(project_dir: impl AsRef<Path>) -> Result<Self> {
112        let conversations_dir = project_dir.as_ref().join(".mermaid").join("conversations");
113
114        // Create conversations directory if it doesn't exist
115        fs::create_dir_all(&conversations_dir)?;
116
117        Ok(Self { conversations_dir })
118    }
119
120    /// Save a conversation to disk
121    pub fn save_conversation(&self, conversation: &ConversationHistory) -> Result<()> {
122        let filename = format!("{}.json", conversation.id);
123        let path = self.conversations_dir.join(filename);
124
125        let json = serde_json::to_string_pretty(conversation)?;
126        fs::write(path, json)?;
127
128        Ok(())
129    }
130
131    /// Load a specific conversation by ID
132    pub fn load_conversation(&self, id: &str) -> Result<ConversationHistory> {
133        let filename = format!("{}.json", id);
134        let path = self.conversations_dir.join(filename);
135
136        let json = fs::read_to_string(path)?;
137        let conversation: ConversationHistory = serde_json::from_str(&json)?;
138
139        Ok(conversation)
140    }
141
142    /// Load the most recent conversation
143    pub fn load_last_conversation(&self) -> Result<Option<ConversationHistory>> {
144        let conversations = self.list_conversations()?;
145
146        if conversations.is_empty() {
147            return Ok(None);
148        }
149
150        // Conversations are already sorted by modification time (newest first)
151        Ok(conversations.into_iter().next())
152    }
153
154    /// List all conversations in the project
155    pub fn list_conversations(&self) -> Result<Vec<ConversationHistory>> {
156        let mut conversations = Vec::new();
157
158        // Read all JSON files in the conversations directory
159        if let Ok(entries) = fs::read_dir(&self.conversations_dir) {
160            for entry in entries.flatten() {
161                if let Some(ext) = entry.path().extension()
162                    && ext == "json"
163                        && let Ok(json) = fs::read_to_string(entry.path())
164                            && let Ok(conv) = serde_json::from_str::<ConversationHistory>(&json) {
165                                conversations.push(conv);
166                            }
167            }
168        }
169
170        // Sort by updated_at (newest first)
171        conversations.sort_by(|a, b| b.updated_at.cmp(&a.updated_at));
172
173        Ok(conversations)
174    }
175
176    /// Delete a conversation
177    pub fn delete_conversation(&self, id: &str) -> Result<()> {
178        let filename = format!("{}.json", id);
179        let path = self.conversations_dir.join(filename);
180
181        if path.exists() {
182            fs::remove_file(path)?;
183        }
184
185        Ok(())
186    }
187
188    /// Get the conversations directory path
189    pub fn conversations_dir(&self) -> &Path {
190        &self.conversations_dir
191    }
192}