1use std::{
2 fs,
3 io::{self, BufRead, Write},
4 path::{Path, PathBuf},
5 time::{SystemTime, UNIX_EPOCH},
6};
7
8use uuid::Uuid;
9
10use serde::{Deserialize, Serialize};
11
12use crate::{mode::AgentMode, provider::Message, provider::TokenUsage};
13
14#[derive(Debug, Clone, Serialize, Deserialize)]
18pub struct SessionMeta {
19 pub id: String,
21 pub working_dir: String,
23 pub created_at: u64,
25 pub updated_at: u64,
27 pub mode: AgentMode,
29 pub provider: String,
31 pub model: Option<String>,
33 pub name: Option<String>,
35 pub message_count: usize,
37 #[serde(default)]
41 pub token_usage: Option<TokenUsage>,
42 #[serde(default)]
44 pub total_tool_calls: u64,
45 #[serde(default)]
47 pub total_tokens_used: u64,
48}
49
50#[derive(Debug, Clone, Serialize, Deserialize)]
52#[serde(tag = "type")]
53pub enum SessionEntry {
54 #[serde(rename = "meta")]
56 Meta(SessionMeta),
57 #[serde(rename = "message")]
59 Message(Message),
60}
61
62#[derive(Debug)]
66pub enum SessionError {
67 Io(std::io::Error),
68 Parse(serde_json::Error),
69 NotFound(String),
70}
71
72impl std::fmt::Display for SessionError {
73 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
74 match self {
75 SessionError::Io(e) => write!(f, "I/O error: {}", e),
76 SessionError::Parse(e) => write!(f, "parse error: {}", e),
77 SessionError::NotFound(s) => write!(f, "{}", s),
78 }
79 }
80}
81
82impl std::error::Error for SessionError {
83 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
84 match self {
85 SessionError::Io(e) => Some(e),
86 SessionError::Parse(e) => Some(e),
87 SessionError::NotFound(_) => None,
88 }
89 }
90}
91
92impl From<std::io::Error> for SessionError {
93 fn from(e: std::io::Error) -> Self {
94 SessionError::Io(e)
95 }
96}
97
98impl From<serde_json::Error> for SessionError {
99 fn from(e: serde_json::Error) -> Self {
100 SessionError::Parse(e)
101 }
102}
103
104pub struct SessionStore {
111 dir: PathBuf,
112}
113
114impl SessionStore {
115 pub fn default_path() -> Self {
122 Self::from_paths(&crate::paths::Paths::default())
123 }
124
125 pub fn from_paths(paths: &crate::paths::Paths) -> Self {
127 SessionStore {
128 dir: paths.sessions_dir(),
129 }
130 }
131
132 pub fn new(dir: PathBuf) -> Self {
134 SessionStore { dir }
135 }
136
137 pub fn ensure_dir(&self) -> Result<(), SessionError> {
139 fs::create_dir_all(&self.dir)?;
140 Ok(())
141 }
142
143 pub fn create(
146 &self,
147 working_dir: &str,
148 mode: AgentMode,
149 provider: &str,
150 model: Option<String>,
151 ) -> Session {
152 let id = Uuid::new_v4().to_string();
153 let now = now_timestamp();
154 let auto_name = std::path::Path::new(working_dir)
155 .file_name()
156 .and_then(|n| n.to_str())
157 .unwrap_or("session")
158 .to_string();
159
160 let meta = SessionMeta {
161 id,
162 working_dir: working_dir.to_string(),
163 created_at: now,
164 updated_at: now,
165 mode,
166 provider: provider.to_string(),
167 model,
168 name: Some(auto_name),
169 message_count: 0,
170 token_usage: None,
171 total_tool_calls: 0,
172 total_tokens_used: 0,
173 };
174
175 let mut session = Session {
177 meta: meta.clone(),
178 path: self.dir.join(format!("{}.jsonl", meta.id)),
179 dirty: true,
180 messages_since_save: 0,
181 created: false,
182 };
183 session.ensure_created();
184 session
185 }
186
187 pub fn load(&self, session_id: &str) -> Result<(Session, Vec<Message>), SessionError> {
190 let path = self.dir.join(format!("{}.jsonl", session_id));
191
192 if !path.exists() {
193 return Err(SessionError::NotFound(format!(
194 "Session '{}' not found",
195 session_id
196 )));
197 }
198
199 let file = fs::File::open(&path)?;
200 let reader = io::BufReader::new(file);
201
202 let mut meta: Option<SessionMeta> = None;
203 let mut messages: Vec<Message> = Vec::new();
204
205 for line in reader.lines() {
206 let line = line?;
207 let trimmed = line.trim();
208 if trimmed.is_empty() {
209 continue;
210 }
211 match serde_json::from_str::<SessionEntry>(trimmed) {
212 Ok(SessionEntry::Meta(m)) => {
213 meta = Some(m);
214 }
215 Ok(SessionEntry::Message(msg)) => {
216 messages.push(msg);
217 }
218 Err(_) => {
219 }
221 }
222 }
223
224 let meta = meta.ok_or_else(|| {
225 SessionError::Parse(serde_json::from_str::<SessionEntry>("").unwrap_err())
226 })?;
227
228 let session = Session {
229 meta: meta.clone(),
230 path,
231 dirty: false,
232 messages_since_save: 0,
233 created: true,
234 };
235
236 Ok((session, messages))
237 }
238
239 pub fn find_latest_for_dir(&self, working_dir: &str) -> Option<String> {
241 if !self.dir.exists() {
242 return None;
243 }
244
245 let entries = fs::read_dir(&self.dir).ok()?;
246 let mut best: Option<(u64, String)> = None;
247
248 for entry in entries.flatten() {
249 let path = entry.path();
250 if path.extension().and_then(|e| e.to_str()) != Some("jsonl") {
251 continue;
252 }
253
254 if let Some(meta) = read_session_meta(&path)
255 && meta.working_dir == working_dir
256 {
257 match &mut best {
258 Some((best_time, best_id)) => {
259 if meta.updated_at > *best_time {
260 *best_time = meta.updated_at;
261 *best_id = meta.id.clone();
262 }
263 }
264 None => {
265 best = Some((meta.updated_at, meta.id.clone()));
266 }
267 }
268 }
269 }
270
271 best.map(|(_, id)| id)
272 }
273
274 pub fn find_by_prefix(&self, prefix: &str) -> Result<String, SessionError> {
276 let all = self.list_all();
277 let matches: Vec<&SessionMeta> = all.iter().filter(|m| m.id.starts_with(prefix)).collect();
278
279 match matches.len() {
280 0 => Err(SessionError::NotFound(format!(
281 "No session found matching '{}'",
282 prefix
283 ))),
284 1 => Ok(matches[0].id.clone()),
285 _ => {
286 let ids: Vec<&str> = matches
287 .iter()
288 .map(|m| &m.id[..12.min(m.id.len())])
289 .collect();
290 Err(SessionError::NotFound(format!(
291 "Multiple sessions match '{}': {}",
292 prefix,
293 ids.join(", ")
294 )))
295 }
296 }
297 }
298
299 pub fn list_all(&self) -> Vec<SessionMeta> {
301 if !self.dir.exists() {
302 return Vec::new();
303 }
304
305 let mut sessions: Vec<SessionMeta> = Vec::new();
306
307 if let Ok(entries) = fs::read_dir(&self.dir) {
308 for entry in entries.flatten() {
309 let path = entry.path();
310 if path.extension().and_then(|e| e.to_str()) != Some("jsonl") {
311 continue;
312 }
313
314 if let Some(meta) = read_session_meta(&path) {
315 sessions.push(meta);
316 }
317 }
318 }
319
320 sessions.sort_by_key(|b| std::cmp::Reverse(b.updated_at));
321 sessions
322 }
323
324 pub fn dir(&self) -> &PathBuf {
326 &self.dir
327 }
328
329 pub fn delete(&self, session_id: &str) -> Result<(), SessionError> {
331 let path = self.dir.join(format!("{}.jsonl", session_id));
332
333 if !path.exists() {
334 return Err(SessionError::NotFound(format!(
335 "Session '{}' not found",
336 session_id
337 )));
338 }
339
340 fs::remove_file(&path)?;
341 Ok(())
342 }
343}
344
345fn now_timestamp() -> u64 {
348 SystemTime::now()
349 .duration_since(UNIX_EPOCH)
350 .unwrap_or_default()
351 .as_secs()
352}
353
354fn read_session_meta(path: &PathBuf) -> Option<SessionMeta> {
355 let file = fs::File::open(path).ok()?;
356 let mut reader = io::BufReader::new(file);
357 let mut first_line = String::new();
358 if reader.read_line(&mut first_line).ok()? == 0 {
359 return None;
360 }
361 if let Ok(SessionEntry::Meta(meta)) = serde_json::from_str::<SessionEntry>(first_line.trim()) {
362 Some(meta)
363 } else {
364 None
365 }
366}
367
368pub struct Session {
375 meta: SessionMeta,
376 path: PathBuf,
377 dirty: bool,
378 messages_since_save: usize,
379 created: bool,
380}
381
382const AUTO_SAVE_INTERVAL: usize = 5;
384
385impl Session {
386 pub fn append_message(&mut self, message: &Message) {
390 self.ensure_created();
391 self.write_entry(&SessionEntry::Message(message.clone()));
392 self.meta.message_count += 1;
393 self.meta.updated_at = now_timestamp();
394 self.dirty = true;
395 self.messages_since_save += 1;
396 if self.messages_since_save >= AUTO_SAVE_INTERVAL {
397 self.flush();
398 self.messages_since_save = 0;
399 }
400 }
401
402 pub fn set_mode(&mut self, mode: AgentMode) {
404 self.meta.mode = mode;
405 self.meta.updated_at = now_timestamp();
406 self.dirty = true;
407 }
408
409 pub fn set_model(&mut self, model: Option<String>) {
411 self.meta.model = model;
412 self.meta.updated_at = now_timestamp();
413 self.dirty = true;
414 }
415
416 pub fn set_name(&mut self, name: String) {
418 self.meta.name = Some(name);
419 self.meta.updated_at = now_timestamp();
420 self.dirty = true;
421 }
422
423 pub fn set_token_usage(&mut self, usage: TokenUsage) {
426 self.meta.token_usage = Some(usage);
427 self.meta.updated_at = now_timestamp();
428 self.dirty = true;
429 }
430
431 pub fn add_tool_calls(&mut self, count: u64) {
433 self.meta.total_tool_calls += count;
434 self.meta.updated_at = now_timestamp();
435 self.dirty = true;
436 }
437
438 pub fn add_tokens_used(&mut self, count: u64) {
440 self.meta.total_tokens_used += count;
441 self.meta.updated_at = now_timestamp();
442 self.dirty = true;
443 }
444
445 pub fn flush(&mut self) {
447 if !self.dirty {
448 return;
449 }
450
451 self.ensure_created();
452
453 let file = match fs::read_to_string(&self.path) {
454 Ok(content) => content,
455 Err(_) => return,
456 };
457
458 let lines: Vec<&str> = file.lines().collect();
459 if lines.is_empty() {
460 return;
461 }
462
463 let meta_line = match serde_json::to_string(&SessionEntry::Meta(self.meta.clone())) {
464 Ok(l) => l,
465 Err(_) => return,
466 };
467
468 let tmp_path = self.path.with_extension("jsonl.tmp");
469
470 match fs::File::create(&tmp_path) {
471 Ok(mut file) => {
472 if writeln!(file, "{}", meta_line).is_err() {
473 let _ = fs::remove_file(&tmp_path);
474 return;
475 }
476 for line in lines.iter().skip(1) {
477 if writeln!(file, "{}", line).is_err() {
478 let _ = fs::remove_file(&tmp_path);
479 return;
480 }
481 }
482 if file.flush().is_err() {
483 let _ = fs::remove_file(&tmp_path);
484 return;
485 }
486 }
487 Err(_) => return,
488 }
489
490 if fs::rename(&tmp_path, &self.path).is_err() {
491 let _ = fs::remove_file(&tmp_path);
492 }
493
494 self.dirty = false;
495 }
496
497 pub fn id(&self) -> &str {
500 &self.meta.id
501 }
502
503 pub fn path(&self) -> &Path {
505 &self.path
506 }
507
508 pub fn meta(&self) -> &SessionMeta {
509 &self.meta
510 }
511
512 fn ensure_created(&mut self) {
515 if self.created {
516 return;
517 }
518
519 let _ = fs::create_dir_all(
521 self.path
522 .parent()
523 .unwrap_or_else(|| std::path::Path::new(".")),
524 );
525
526 self.write_entry(&SessionEntry::Meta(self.meta.clone()));
527 self.created = true;
528 }
529
530 fn write_entry(&self, entry: &SessionEntry) {
531 let line = match serde_json::to_string(entry) {
532 Ok(l) => l,
533 Err(_) => return,
534 };
535
536 if let Ok(mut file) = fs::OpenOptions::new()
537 .create(true)
538 .append(true)
539 .open(&self.path)
540 {
541 let _ = writeln!(file, "{}", line);
542 }
543 }
544}
545
546impl Drop for Session {
547 fn drop(&mut self) {
548 if self.created {
549 self.flush();
550 }
551 }
552}
553
554pub fn format_age(secs: u64) -> String {
556 if secs < 60 {
557 format!("{}s ago", secs)
558 } else if secs < 3600 {
559 format!("{}m ago", secs / 60)
560 } else if secs < 86400 {
561 format!("{}h ago", secs / 3600)
562 } else {
563 format!("{}d ago", secs / 86400)
564 }
565}