1use std::{
2 fs,
3 io::{self, BufRead, Write},
4 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 {
118 let home = std::env::var("HOME").unwrap_or_else(|_| ".".to_string());
119 let dir = PathBuf::from(home).join(".local/share/tinyharness/sessions");
120 SessionStore { dir }
121 }
122
123 pub fn new(dir: PathBuf) -> Self {
125 SessionStore { dir }
126 }
127
128 pub fn ensure_dir(&self) -> Result<(), SessionError> {
130 fs::create_dir_all(&self.dir)?;
131 Ok(())
132 }
133
134 pub fn create(
137 &self,
138 working_dir: &str,
139 mode: AgentMode,
140 provider: &str,
141 model: Option<String>,
142 ) -> Session {
143 let id = Uuid::new_v4().to_string();
144 let now = now_timestamp();
145 let auto_name = std::path::Path::new(working_dir)
146 .file_name()
147 .and_then(|n| n.to_str())
148 .unwrap_or("session")
149 .to_string();
150
151 let meta = SessionMeta {
152 id,
153 working_dir: working_dir.to_string(),
154 created_at: now,
155 updated_at: now,
156 mode,
157 provider: provider.to_string(),
158 model,
159 name: Some(auto_name),
160 message_count: 0,
161 token_usage: None,
162 total_tool_calls: 0,
163 total_tokens_used: 0,
164 };
165
166 let mut session = Session {
168 meta: meta.clone(),
169 path: self.dir.join(format!("{}.jsonl", meta.id)),
170 dirty: true,
171 messages_since_save: 0,
172 created: false,
173 };
174 session.ensure_created();
175 session
176 }
177
178 pub fn load(&self, session_id: &str) -> Result<(Session, Vec<Message>), SessionError> {
181 let path = self.dir.join(format!("{}.jsonl", session_id));
182
183 if !path.exists() {
184 return Err(SessionError::NotFound(format!(
185 "Session '{}' not found",
186 session_id
187 )));
188 }
189
190 let file = fs::File::open(&path)?;
191 let reader = io::BufReader::new(file);
192
193 let mut meta: Option<SessionMeta> = None;
194 let mut messages: Vec<Message> = Vec::new();
195
196 for line in reader.lines() {
197 let line = line?;
198 let trimmed = line.trim();
199 if trimmed.is_empty() {
200 continue;
201 }
202 match serde_json::from_str::<SessionEntry>(trimmed) {
203 Ok(SessionEntry::Meta(m)) => {
204 meta = Some(m);
205 }
206 Ok(SessionEntry::Message(msg)) => {
207 messages.push(msg);
208 }
209 Err(_) => {
210 }
212 }
213 }
214
215 let meta = meta.ok_or_else(|| {
216 SessionError::Parse(serde_json::from_str::<SessionEntry>("").unwrap_err())
217 })?;
218
219 let session = Session {
220 meta: meta.clone(),
221 path,
222 dirty: false,
223 messages_since_save: 0,
224 created: true,
225 };
226
227 Ok((session, messages))
228 }
229
230 pub fn find_latest_for_dir(&self, working_dir: &str) -> Option<String> {
232 if !self.dir.exists() {
233 return None;
234 }
235
236 let entries = fs::read_dir(&self.dir).ok()?;
237 let mut best: Option<(u64, String)> = None;
238
239 for entry in entries.flatten() {
240 let path = entry.path();
241 if path.extension().and_then(|e| e.to_str()) != Some("jsonl") {
242 continue;
243 }
244
245 if let Some(meta) = read_session_meta(&path)
246 && meta.working_dir == working_dir
247 {
248 match &mut best {
249 Some((best_time, best_id)) => {
250 if meta.updated_at > *best_time {
251 *best_time = meta.updated_at;
252 *best_id = meta.id.clone();
253 }
254 }
255 None => {
256 best = Some((meta.updated_at, meta.id.clone()));
257 }
258 }
259 }
260 }
261
262 best.map(|(_, id)| id)
263 }
264
265 pub fn find_by_prefix(&self, prefix: &str) -> Result<String, SessionError> {
267 let all = self.list_all();
268 let matches: Vec<&SessionMeta> = all.iter().filter(|m| m.id.starts_with(prefix)).collect();
269
270 match matches.len() {
271 0 => Err(SessionError::NotFound(format!(
272 "No session found matching '{}'",
273 prefix
274 ))),
275 1 => Ok(matches[0].id.clone()),
276 _ => {
277 let ids: Vec<&str> = matches
278 .iter()
279 .map(|m| &m.id[..12.min(m.id.len())])
280 .collect();
281 Err(SessionError::NotFound(format!(
282 "Multiple sessions match '{}': {}",
283 prefix,
284 ids.join(", ")
285 )))
286 }
287 }
288 }
289
290 pub fn list_all(&self) -> Vec<SessionMeta> {
292 if !self.dir.exists() {
293 return Vec::new();
294 }
295
296 let mut sessions: Vec<SessionMeta> = Vec::new();
297
298 if let Ok(entries) = fs::read_dir(&self.dir) {
299 for entry in entries.flatten() {
300 let path = entry.path();
301 if path.extension().and_then(|e| e.to_str()) != Some("jsonl") {
302 continue;
303 }
304
305 if let Some(meta) = read_session_meta(&path) {
306 sessions.push(meta);
307 }
308 }
309 }
310
311 sessions.sort_by_key(|b| std::cmp::Reverse(b.updated_at));
312 sessions
313 }
314
315 pub fn dir(&self) -> &PathBuf {
317 &self.dir
318 }
319
320 pub fn delete(&self, session_id: &str) -> Result<(), SessionError> {
322 let path = self.dir.join(format!("{}.jsonl", session_id));
323
324 if !path.exists() {
325 return Err(SessionError::NotFound(format!(
326 "Session '{}' not found",
327 session_id
328 )));
329 }
330
331 fs::remove_file(&path)?;
332 Ok(())
333 }
334}
335
336fn now_timestamp() -> u64 {
339 SystemTime::now()
340 .duration_since(UNIX_EPOCH)
341 .unwrap_or_default()
342 .as_secs()
343}
344
345fn read_session_meta(path: &PathBuf) -> Option<SessionMeta> {
346 let file = fs::File::open(path).ok()?;
347 let mut reader = io::BufReader::new(file);
348 let mut first_line = String::new();
349 if reader.read_line(&mut first_line).ok()? == 0 {
350 return None;
351 }
352 if let Ok(SessionEntry::Meta(meta)) = serde_json::from_str::<SessionEntry>(first_line.trim()) {
353 Some(meta)
354 } else {
355 None
356 }
357}
358
359pub struct Session {
366 meta: SessionMeta,
367 path: PathBuf,
368 dirty: bool,
369 messages_since_save: usize,
370 created: bool,
371}
372
373const AUTO_SAVE_INTERVAL: usize = 5;
375
376impl Session {
377 pub fn append_message(&mut self, message: &Message) {
381 self.ensure_created();
382 self.write_entry(&SessionEntry::Message(message.clone()));
383 self.meta.message_count += 1;
384 self.meta.updated_at = now_timestamp();
385 self.dirty = true;
386 self.messages_since_save += 1;
387 if self.messages_since_save >= AUTO_SAVE_INTERVAL {
388 self.flush();
389 self.messages_since_save = 0;
390 }
391 }
392
393 pub fn set_mode(&mut self, mode: AgentMode) {
395 self.meta.mode = mode;
396 self.meta.updated_at = now_timestamp();
397 self.dirty = true;
398 }
399
400 pub fn set_model(&mut self, model: Option<String>) {
402 self.meta.model = model;
403 self.meta.updated_at = now_timestamp();
404 self.dirty = true;
405 }
406
407 pub fn set_name(&mut self, name: String) {
409 self.meta.name = Some(name);
410 self.meta.updated_at = now_timestamp();
411 self.dirty = true;
412 }
413
414 pub fn set_token_usage(&mut self, usage: TokenUsage) {
417 self.meta.token_usage = Some(usage);
418 self.meta.updated_at = now_timestamp();
419 self.dirty = true;
420 }
421
422 pub fn add_tool_calls(&mut self, count: u64) {
424 self.meta.total_tool_calls += count;
425 self.meta.updated_at = now_timestamp();
426 self.dirty = true;
427 }
428
429 pub fn add_tokens_used(&mut self, count: u64) {
431 self.meta.total_tokens_used += count;
432 self.meta.updated_at = now_timestamp();
433 self.dirty = true;
434 }
435
436 pub fn flush(&mut self) {
438 if !self.dirty {
439 return;
440 }
441
442 self.ensure_created();
443
444 let file = match fs::read_to_string(&self.path) {
445 Ok(content) => content,
446 Err(_) => return,
447 };
448
449 let lines: Vec<&str> = file.lines().collect();
450 if lines.is_empty() {
451 return;
452 }
453
454 let meta_line = match serde_json::to_string(&SessionEntry::Meta(self.meta.clone())) {
455 Ok(l) => l,
456 Err(_) => return,
457 };
458
459 let tmp_path = self.path.with_extension("jsonl.tmp");
460
461 match fs::File::create(&tmp_path) {
462 Ok(mut file) => {
463 if writeln!(file, "{}", meta_line).is_err() {
464 let _ = fs::remove_file(&tmp_path);
465 return;
466 }
467 for line in lines.iter().skip(1) {
468 if writeln!(file, "{}", line).is_err() {
469 let _ = fs::remove_file(&tmp_path);
470 return;
471 }
472 }
473 if file.flush().is_err() {
474 let _ = fs::remove_file(&tmp_path);
475 return;
476 }
477 }
478 Err(_) => return,
479 }
480
481 if fs::rename(&tmp_path, &self.path).is_err() {
482 let _ = fs::remove_file(&tmp_path);
483 }
484
485 self.dirty = false;
486 }
487
488 pub fn id(&self) -> &str {
491 &self.meta.id
492 }
493
494 pub fn meta(&self) -> &SessionMeta {
495 &self.meta
496 }
497
498 fn ensure_created(&mut self) {
501 if self.created {
502 return;
503 }
504
505 let _ = fs::create_dir_all(
507 self.path
508 .parent()
509 .unwrap_or_else(|| std::path::Path::new(".")),
510 );
511
512 self.write_entry(&SessionEntry::Meta(self.meta.clone()));
513 self.created = true;
514 }
515
516 fn write_entry(&self, entry: &SessionEntry) {
517 let line = match serde_json::to_string(entry) {
518 Ok(l) => l,
519 Err(_) => return,
520 };
521
522 if let Ok(mut file) = fs::OpenOptions::new()
523 .create(true)
524 .append(true)
525 .open(&self.path)
526 {
527 let _ = writeln!(file, "{}", line);
528 }
529 }
530}
531
532impl Drop for Session {
533 fn drop(&mut self) {
534 if self.created {
535 self.flush();
536 }
537 }
538}
539
540pub fn format_age(secs: u64) -> String {
542 if secs < 60 {
543 format!("{}s ago", secs)
544 } else if secs < 3600 {
545 format!("{}m ago", secs / 60)
546 } else if secs < 86400 {
547 format!("{}h ago", secs / 3600)
548 } else {
549 format!("{}d ago", secs / 86400)
550 }
551}