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}