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 return;
62 }
63
64 if self.input_history.len() >= 100 {
66 self.input_history.pop_front(); }
68
69 self.input_history.push_back(input);
70 }
71
72 fn update_title(&mut self) {
74 if let Some(first_user_msg) = self.messages.iter().find(|m| m.role == MessageRole::User) {
75 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 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
104pub struct ConversationManager {
106 conversations_dir: PathBuf,
107}
108
109impl ConversationManager {
110 pub fn new(project_dir: impl AsRef<Path>) -> Result<Self> {
112 let conversations_dir = project_dir.as_ref().join(".mermaid").join("conversations");
113
114 fs::create_dir_all(&conversations_dir)?;
116
117 Ok(Self { conversations_dir })
118 }
119
120 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 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 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 Ok(conversations.into_iter().next())
152 }
153
154 pub fn list_conversations(&self) -> Result<Vec<ConversationHistory>> {
156 let mut conversations = Vec::new();
157
158 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 conversations.sort_by(|a, b| b.updated_at.cmp(&a.updated_at));
172
173 Ok(conversations)
174 }
175
176 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 pub fn conversations_dir(&self) -> &Path {
190 &self.conversations_dir
191 }
192}