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"));
30 Self {
31 id: id.clone(),
32 title: format!("Session {}", now.format("%Y-%m-%d %H:%M")),
33 messages: Vec::new(),
34 model_name,
35 project_path,
36 created_at: now,
37 updated_at: now,
38 total_tokens: None,
39 input_history: VecDeque::new(),
40 }
41 }
42
43 pub fn add_messages(&mut self, messages: &[ChatMessage]) {
45 self.messages.extend_from_slice(messages);
46 self.updated_at = Local::now();
47 self.update_title();
48 }
49
50 pub fn add_to_input_history(&mut self, input: String) {
52 if input.trim().is_empty() {
54 return;
55 }
56
57 if let Some(last) = self.input_history.back() {
59 if last == &input {
60 return;
61 }
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 if ext == "json" {
163 if let Ok(json) = fs::read_to_string(entry.path()) {
164 if let Ok(conv) = serde_json::from_str::<ConversationHistory>(&json) {
165 conversations.push(conv);
166 }
167 }
168 }
169 }
170 }
171 }
172
173 conversations.sort_by(|a, b| b.updated_at.cmp(&a.updated_at));
175
176 Ok(conversations)
177 }
178
179 pub fn delete_conversation(&self, id: &str) -> Result<()> {
181 let filename = format!("{}.json", id);
182 let path = self.conversations_dir.join(filename);
183
184 if path.exists() {
185 fs::remove_file(path)?;
186 }
187
188 Ok(())
189 }
190
191 pub fn conversations_dir(&self) -> &Path {
193 &self.conversations_dir
194 }
195}