agent_storage/conversation/
conversation_store.rs1use super::{Conversation, ConversationId, ConversationStoreError, default_conversation_title};
4use crate::FamilyId;
5use agent_runtime::Message;
6use chrono::Utc;
7use std::{
8 collections::HashMap,
9 fs::{self, OpenOptions},
10 io::{self, Write},
11 path::{Path, PathBuf},
12 sync::Mutex,
13};
14use uuid::Uuid;
15
16pub struct ConversationStore {
22 root: PathBuf,
23 lock: Mutex<()>,
24}
25
26impl ConversationStore {
27 pub fn open(root: impl Into<PathBuf>) -> Result<Self, ConversationStoreError> {
28 let root = root.into();
29 fs::create_dir_all(root.join("conversations"))?;
30 Ok(Self {
31 root,
32 lock: Mutex::new(()),
33 })
34 }
35
36 pub fn create(
38 &self,
39 owner: impl Into<String>,
40 agent: impl Into<String>,
41 ) -> Result<Conversation, ConversationStoreError> {
42 let owner = owner.into();
43 let agent = agent.into();
44 if owner.trim().is_empty() {
45 return Err(ConversationStoreError::EmptyOwner);
46 }
47 if agent.trim().is_empty() {
48 return Err(ConversationStoreError::EmptyAgent);
49 }
50
51 let _guard = self
52 .lock
53 .lock()
54 .unwrap_or_else(|poisoned| poisoned.into_inner());
55 let now = Utc::now();
56 let conversation = Conversation {
57 id: ConversationId::new(),
58 owner: owner.clone(),
59 agent,
60 title: default_conversation_title(),
61 archived: false,
62 selected_family_id: None,
63 created_at: now,
64 updated_at: now,
65 messages: Vec::new(),
66 };
67
68 self.write_conversation(&conversation)?;
69 let mut active = self.read_active_index()?;
70 active.insert(owner, conversation.id);
71 self.write_active_index(&active)?;
72
73 Ok(conversation)
74 }
75
76 pub fn active(&self, owner: &str) -> Result<Option<Conversation>, ConversationStoreError> {
78 let _guard = self
79 .lock
80 .lock()
81 .unwrap_or_else(|poisoned| poisoned.into_inner());
82 let active = self.read_active_index()?;
83 active
84 .get(owner)
85 .copied()
86 .map(|id| self.read_conversation(id))
87 .transpose()
88 }
89
90 pub fn list(&self, owner: &str) -> Result<Vec<Conversation>, ConversationStoreError> {
92 self.list_with_archive_state(owner, false)
93 }
94
95 pub fn list_archived(&self, owner: &str) -> Result<Vec<Conversation>, ConversationStoreError> {
97 self.list_with_archive_state(owner, true)
98 }
99
100 fn list_with_archive_state(
101 &self,
102 owner: &str,
103 archived: bool,
104 ) -> Result<Vec<Conversation>, ConversationStoreError> {
105 let _guard = self
106 .lock
107 .lock()
108 .unwrap_or_else(|poisoned| poisoned.into_inner());
109 let directory = self.root.join("conversations");
110 let mut conversations = Vec::new();
111
112 for entry in fs::read_dir(directory)? {
113 let entry = entry?;
114 if !entry.file_type()?.is_file()
115 || entry
116 .path()
117 .extension()
118 .and_then(|extension| extension.to_str())
119 != Some("json")
120 {
121 continue;
122 }
123
124 let bytes = fs::read(entry.path())?;
125 let conversation: Conversation = serde_json::from_slice(&bytes)?;
126 if conversation.owner == owner && conversation.archived == archived {
127 conversations.push(conversation);
128 }
129 }
130
131 conversations.sort_by(|left, right| {
132 right
133 .updated_at
134 .cmp(&left.updated_at)
135 .then_with(|| right.id.to_string().cmp(&left.id.to_string()))
136 });
137 Ok(conversations)
138 }
139
140 pub fn set_active(
142 &self,
143 owner: &str,
144 id: ConversationId,
145 ) -> Result<(), ConversationStoreError> {
146 let _guard = self
147 .lock
148 .lock()
149 .unwrap_or_else(|poisoned| poisoned.into_inner());
150 let conversation = self.read_conversation(id)?;
151 if conversation.owner != owner {
152 return Err(ConversationStoreError::OwnerMismatch {
153 conversation_id: id,
154 owner: owner.to_owned(),
155 });
156 }
157
158 let mut active = self.read_active_index()?;
159 active.insert(owner.to_owned(), id);
160 self.write_active_index(&active)
161 }
162
163 pub fn get(&self, id: ConversationId) -> Result<Conversation, ConversationStoreError> {
165 let _guard = self
166 .lock
167 .lock()
168 .unwrap_or_else(|poisoned| poisoned.into_inner());
169 self.read_conversation(id)
170 }
171
172 pub fn rename(
174 &self,
175 owner: &str,
176 id: ConversationId,
177 title: impl Into<String>,
178 ) -> Result<Conversation, ConversationStoreError> {
179 let title = title.into();
180 let title = title.trim();
181 if title.is_empty() {
182 return Err(ConversationStoreError::EmptyTitle);
183 }
184
185 let _guard = self
186 .lock
187 .lock()
188 .unwrap_or_else(|poisoned| poisoned.into_inner());
189 let mut conversation = self.read_conversation(id)?;
190 if conversation.owner != owner {
191 return Err(ConversationStoreError::OwnerMismatch {
192 conversation_id: id,
193 owner: owner.to_owned(),
194 });
195 }
196
197 conversation.title = title.to_owned();
198 conversation.updated_at = Utc::now();
199 self.write_conversation(&conversation)?;
200 Ok(conversation)
201 }
202
203 pub fn set_selected_family(
205 &self,
206 owner: &str,
207 id: ConversationId,
208 family_id: Option<FamilyId>,
209 ) -> Result<Conversation, ConversationStoreError> {
210 let _guard = self
211 .lock
212 .lock()
213 .unwrap_or_else(|poisoned| poisoned.into_inner());
214 let mut conversation = self.read_conversation(id)?;
215 if conversation.owner != owner {
216 return Err(ConversationStoreError::OwnerMismatch {
217 conversation_id: id,
218 owner: owner.to_owned(),
219 });
220 }
221 conversation.selected_family_id = family_id;
222 conversation.updated_at = Utc::now();
223 self.write_conversation(&conversation)?;
224 Ok(conversation)
225 }
226
227 pub fn set_archived(
233 &self,
234 owner: &str,
235 id: ConversationId,
236 archived: bool,
237 ) -> Result<Conversation, ConversationStoreError> {
238 let _guard = self
239 .lock
240 .lock()
241 .unwrap_or_else(|poisoned| poisoned.into_inner());
242 let mut conversation = self.read_conversation(id)?;
243 if conversation.owner != owner {
244 return Err(ConversationStoreError::OwnerMismatch {
245 conversation_id: id,
246 owner: owner.to_owned(),
247 });
248 }
249
250 conversation.archived = archived;
251 self.write_conversation(&conversation)?;
252
253 if archived {
254 let mut active = self.read_active_index()?;
255 if active.get(owner) == Some(&id) {
256 active.remove(owner);
257 self.write_active_index(&active)?;
258 }
259 }
260
261 Ok(conversation)
262 }
263
264 pub fn delete(&self, owner: &str, id: ConversationId) -> Result<(), ConversationStoreError> {
269 let _guard = self
270 .lock
271 .lock()
272 .unwrap_or_else(|poisoned| poisoned.into_inner());
273 let conversation = self.read_conversation(id)?;
274 if conversation.owner != owner {
275 return Err(ConversationStoreError::OwnerMismatch {
276 conversation_id: id,
277 owner: owner.to_owned(),
278 });
279 }
280
281 let mut active = self.read_active_index()?;
282 if active.get(owner) == Some(&id) {
283 active.remove(owner);
284 self.write_active_index(&active)?;
285 }
286
287 fs::remove_file(self.conversation_path(id))?;
288 Ok(())
289 }
290
291 pub fn save_messages(
293 &self,
294 id: ConversationId,
295 messages: Vec<Message>,
296 ) -> Result<Conversation, ConversationStoreError> {
297 let _guard = self
298 .lock
299 .lock()
300 .unwrap_or_else(|poisoned| poisoned.into_inner());
301 let mut conversation = self.read_conversation(id)?;
302 conversation.messages = messages;
303 conversation.updated_at = Utc::now();
304 self.write_conversation(&conversation)?;
305 Ok(conversation)
306 }
307
308 fn conversation_path(&self, id: ConversationId) -> PathBuf {
309 self.root.join("conversations").join(format!("{id}.json"))
310 }
311
312 fn read_conversation(
313 &self,
314 id: ConversationId,
315 ) -> Result<Conversation, ConversationStoreError> {
316 let path = self.conversation_path(id);
317 match fs::read(path) {
318 Ok(bytes) => Ok(serde_json::from_slice(&bytes)?),
319 Err(error) if error.kind() == io::ErrorKind::NotFound => {
320 Err(ConversationStoreError::NotFound(id))
321 }
322 Err(error) => Err(error.into()),
323 }
324 }
325
326 fn write_conversation(
327 &self,
328 conversation: &Conversation,
329 ) -> Result<(), ConversationStoreError> {
330 let bytes = serde_json::to_vec_pretty(conversation)?;
331 atomic_write(&self.conversation_path(conversation.id), &bytes)?;
332 Ok(())
333 }
334
335 fn read_active_index(&self) -> Result<HashMap<String, ConversationId>, ConversationStoreError> {
336 let path = self.root.join("active-conversations.json");
337 match fs::read(path) {
338 Ok(bytes) => Ok(serde_json::from_slice(&bytes)?),
339 Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(HashMap::new()),
340 Err(error) => Err(error.into()),
341 }
342 }
343
344 fn write_active_index(
345 &self,
346 active: &HashMap<String, ConversationId>,
347 ) -> Result<(), ConversationStoreError> {
348 let bytes = serde_json::to_vec_pretty(active)?;
349 atomic_write(&self.root.join("active-conversations.json"), &bytes)?;
350 Ok(())
351 }
352}
353
354fn atomic_write(path: &Path, contents: &[u8]) -> Result<(), io::Error> {
355 let parent = path.parent().expect("storage file always has a parent");
356 fs::create_dir_all(parent)?;
357
358 let temporary = parent.join(format!(
359 ".{}.{}.tmp",
360 path.file_name().unwrap().to_string_lossy(),
361 Uuid::new_v4()
362 ));
363 let mut file = OpenOptions::new()
364 .write(true)
365 .create_new(true)
366 .open(&temporary)?;
367 let result = (|| {
368 file.write_all(contents)?;
369 file.sync_all()?;
370 fs::rename(&temporary, path)?;
371 Ok(())
372 })();
373
374 if result.is_err() {
375 let _ = fs::remove_file(&temporary);
376 }
377 result
378}