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}
43
44#[derive(Debug, Clone, Serialize, Deserialize)]
46#[serde(tag = "type")]
47pub enum SessionEntry {
48 #[serde(rename = "meta")]
50 Meta(SessionMeta),
51 #[serde(rename = "message")]
53 Message(Message),
54}
55
56#[derive(Debug)]
60pub enum SessionError {
61 Io(std::io::Error),
62 Parse(serde_json::Error),
63 NotFound(String),
64}
65
66impl std::fmt::Display for SessionError {
67 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
68 match self {
69 SessionError::Io(e) => write!(f, "I/O error: {}", e),
70 SessionError::Parse(e) => write!(f, "parse error: {}", e),
71 SessionError::NotFound(s) => write!(f, "{}", s),
72 }
73 }
74}
75
76impl std::error::Error for SessionError {
77 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
78 match self {
79 SessionError::Io(e) => Some(e),
80 SessionError::Parse(e) => Some(e),
81 SessionError::NotFound(_) => None,
82 }
83 }
84}
85
86impl From<std::io::Error> for SessionError {
87 fn from(e: std::io::Error) -> Self {
88 SessionError::Io(e)
89 }
90}
91
92impl From<serde_json::Error> for SessionError {
93 fn from(e: serde_json::Error) -> Self {
94 SessionError::Parse(e)
95 }
96}
97
98pub struct SessionStore {
105 dir: PathBuf,
106}
107
108impl SessionStore {
109 pub fn default_path() -> Self {
112 let home = std::env::var("HOME").unwrap_or_else(|_| ".".to_string());
113 let dir = PathBuf::from(home).join(".local/share/tinyharness/sessions");
114 SessionStore { dir }
115 }
116
117 pub fn new(dir: PathBuf) -> Self {
119 SessionStore { dir }
120 }
121
122 pub fn ensure_dir(&self) -> Result<(), SessionError> {
124 fs::create_dir_all(&self.dir)?;
125 Ok(())
126 }
127
128 pub fn create(
131 &self,
132 working_dir: &str,
133 mode: AgentMode,
134 provider: &str,
135 model: Option<String>,
136 ) -> Session {
137 let id = Uuid::new_v4().to_string();
138 let now = now_timestamp();
139 let auto_name = std::path::Path::new(working_dir)
140 .file_name()
141 .and_then(|n| n.to_str())
142 .unwrap_or("session")
143 .to_string();
144
145 let meta = SessionMeta {
146 id,
147 working_dir: working_dir.to_string(),
148 created_at: now,
149 updated_at: now,
150 mode,
151 provider: provider.to_string(),
152 model,
153 name: Some(auto_name),
154 message_count: 0,
155 token_usage: None,
156 };
157
158 let mut session = Session {
160 meta: meta.clone(),
161 path: self.dir.join(format!("{}.jsonl", meta.id)),
162 dirty: true,
163 messages_since_save: 0,
164 created: false,
165 };
166 session.ensure_created();
167 session
168 }
169
170 pub fn load(&self, session_id: &str) -> Result<(Session, Vec<Message>), SessionError> {
173 let path = self.dir.join(format!("{}.jsonl", session_id));
174
175 if !path.exists() {
176 return Err(SessionError::NotFound(format!(
177 "Session '{}' not found",
178 session_id
179 )));
180 }
181
182 let file = fs::File::open(&path)?;
183 let reader = io::BufReader::new(file);
184
185 let mut meta: Option<SessionMeta> = None;
186 let mut messages: Vec<Message> = Vec::new();
187
188 for line in reader.lines() {
189 let line = line?;
190 let trimmed = line.trim();
191 if trimmed.is_empty() {
192 continue;
193 }
194 match serde_json::from_str::<SessionEntry>(trimmed) {
195 Ok(SessionEntry::Meta(m)) => {
196 meta = Some(m);
197 }
198 Ok(SessionEntry::Message(msg)) => {
199 messages.push(msg);
200 }
201 Err(_) => {
202 }
204 }
205 }
206
207 let meta = meta.ok_or_else(|| {
208 SessionError::Parse(serde_json::from_str::<SessionEntry>("").unwrap_err())
209 })?;
210
211 let session = Session {
212 meta: meta.clone(),
213 path,
214 dirty: false,
215 messages_since_save: 0,
216 created: true,
217 };
218
219 Ok((session, messages))
220 }
221
222 pub fn find_latest_for_dir(&self, working_dir: &str) -> Option<String> {
224 if !self.dir.exists() {
225 return None;
226 }
227
228 let entries = fs::read_dir(&self.dir).ok()?;
229 let mut best: Option<(u64, String)> = None;
230
231 for entry in entries.flatten() {
232 let path = entry.path();
233 if path.extension().and_then(|e| e.to_str()) != Some("jsonl") {
234 continue;
235 }
236
237 if let Some(meta) = read_session_meta(&path)
238 && meta.working_dir == working_dir
239 {
240 match &mut best {
241 Some((best_time, best_id)) => {
242 if meta.updated_at > *best_time {
243 *best_time = meta.updated_at;
244 *best_id = meta.id.clone();
245 }
246 }
247 None => {
248 best = Some((meta.updated_at, meta.id.clone()));
249 }
250 }
251 }
252 }
253
254 best.map(|(_, id)| id)
255 }
256
257 pub fn find_by_prefix(&self, prefix: &str) -> Result<String, SessionError> {
259 let all = self.list_all();
260 let matches: Vec<&SessionMeta> = all.iter().filter(|m| m.id.starts_with(prefix)).collect();
261
262 match matches.len() {
263 0 => Err(SessionError::NotFound(format!(
264 "No session found matching '{}'",
265 prefix
266 ))),
267 1 => Ok(matches[0].id.clone()),
268 _ => {
269 let ids: Vec<&str> = matches
270 .iter()
271 .map(|m| &m.id[..12.min(m.id.len())])
272 .collect();
273 Err(SessionError::NotFound(format!(
274 "Multiple sessions match '{}': {}",
275 prefix,
276 ids.join(", ")
277 )))
278 }
279 }
280 }
281
282 pub fn list_all(&self) -> Vec<SessionMeta> {
284 if !self.dir.exists() {
285 return Vec::new();
286 }
287
288 let mut sessions: Vec<SessionMeta> = Vec::new();
289
290 if let Ok(entries) = fs::read_dir(&self.dir) {
291 for entry in entries.flatten() {
292 let path = entry.path();
293 if path.extension().and_then(|e| e.to_str()) != Some("jsonl") {
294 continue;
295 }
296
297 if let Some(meta) = read_session_meta(&path) {
298 sessions.push(meta);
299 }
300 }
301 }
302
303 sessions.sort_by_key(|b| std::cmp::Reverse(b.updated_at));
304 sessions
305 }
306
307 pub fn dir(&self) -> &PathBuf {
309 &self.dir
310 }
311
312 pub fn delete(&self, session_id: &str) -> Result<(), SessionError> {
314 let path = self.dir.join(format!("{}.jsonl", session_id));
315
316 if !path.exists() {
317 return Err(SessionError::NotFound(format!(
318 "Session '{}' not found",
319 session_id
320 )));
321 }
322
323 fs::remove_file(&path)?;
324 Ok(())
325 }
326}
327
328fn now_timestamp() -> u64 {
331 SystemTime::now()
332 .duration_since(UNIX_EPOCH)
333 .unwrap_or_default()
334 .as_secs()
335}
336
337fn read_session_meta(path: &PathBuf) -> Option<SessionMeta> {
338 let file = fs::File::open(path).ok()?;
339 let mut reader = io::BufReader::new(file);
340 let mut first_line = String::new();
341 if reader.read_line(&mut first_line).ok()? == 0 {
342 return None;
343 }
344 if let Ok(SessionEntry::Meta(meta)) = serde_json::from_str::<SessionEntry>(first_line.trim()) {
345 Some(meta)
346 } else {
347 None
348 }
349}
350
351pub struct Session {
358 meta: SessionMeta,
359 path: PathBuf,
360 dirty: bool,
361 messages_since_save: usize,
362 created: bool,
363}
364
365const AUTO_SAVE_INTERVAL: usize = 5;
367
368impl Session {
369 pub fn append_message(&mut self, message: &Message) {
373 self.ensure_created();
374 self.write_entry(&SessionEntry::Message(message.clone()));
375 self.meta.message_count += 1;
376 self.meta.updated_at = now_timestamp();
377 self.dirty = true;
378 self.messages_since_save += 1;
379 if self.messages_since_save >= AUTO_SAVE_INTERVAL {
380 self.flush();
381 self.messages_since_save = 0;
382 }
383 }
384
385 pub fn set_mode(&mut self, mode: AgentMode) {
387 self.meta.mode = mode;
388 self.meta.updated_at = now_timestamp();
389 self.dirty = true;
390 }
391
392 pub fn set_model(&mut self, model: Option<String>) {
394 self.meta.model = model;
395 self.meta.updated_at = now_timestamp();
396 self.dirty = true;
397 }
398
399 pub fn set_name(&mut self, name: String) {
401 self.meta.name = Some(name);
402 self.meta.updated_at = now_timestamp();
403 self.dirty = true;
404 }
405
406 pub fn set_token_usage(&mut self, usage: TokenUsage) {
409 self.meta.token_usage = Some(usage);
410 self.meta.updated_at = now_timestamp();
411 self.dirty = true;
412 }
413
414 pub fn flush(&mut self) {
416 if !self.dirty {
417 return;
418 }
419
420 self.ensure_created();
421
422 let file = match fs::read_to_string(&self.path) {
423 Ok(content) => content,
424 Err(_) => return,
425 };
426
427 let lines: Vec<&str> = file.lines().collect();
428 if lines.is_empty() {
429 return;
430 }
431
432 let meta_line = match serde_json::to_string(&SessionEntry::Meta(self.meta.clone())) {
433 Ok(l) => l,
434 Err(_) => return,
435 };
436
437 let tmp_path = self.path.with_extension("jsonl.tmp");
438
439 match fs::File::create(&tmp_path) {
440 Ok(mut file) => {
441 if writeln!(file, "{}", meta_line).is_err() {
442 let _ = fs::remove_file(&tmp_path);
443 return;
444 }
445 for line in lines.iter().skip(1) {
446 if writeln!(file, "{}", line).is_err() {
447 let _ = fs::remove_file(&tmp_path);
448 return;
449 }
450 }
451 if file.flush().is_err() {
452 let _ = fs::remove_file(&tmp_path);
453 return;
454 }
455 }
456 Err(_) => return,
457 }
458
459 if fs::rename(&tmp_path, &self.path).is_err() {
460 let _ = fs::remove_file(&tmp_path);
461 }
462
463 self.dirty = false;
464 }
465
466 pub fn id(&self) -> &str {
469 &self.meta.id
470 }
471
472 pub fn meta(&self) -> &SessionMeta {
473 &self.meta
474 }
475
476 fn ensure_created(&mut self) {
479 if self.created {
480 return;
481 }
482
483 let _ = fs::create_dir_all(
485 self.path
486 .parent()
487 .unwrap_or_else(|| std::path::Path::new(".")),
488 );
489
490 self.write_entry(&SessionEntry::Meta(self.meta.clone()));
491 self.created = true;
492 }
493
494 fn write_entry(&self, entry: &SessionEntry) {
495 let line = match serde_json::to_string(entry) {
496 Ok(l) => l,
497 Err(_) => return,
498 };
499
500 if let Ok(mut file) = fs::OpenOptions::new()
501 .create(true)
502 .append(true)
503 .open(&self.path)
504 {
505 let _ = writeln!(file, "{}", line);
506 }
507 }
508}
509
510impl Drop for Session {
511 fn drop(&mut self) {
512 if self.created {
513 self.flush();
514 }
515 }
516}
517
518pub fn format_age(secs: u64) -> String {
520 if secs < 60 {
521 format!("{}s ago", secs)
522 } else if secs < 3600 {
523 format!("{}m ago", secs / 60)
524 } else if secs < 86400 {
525 format!("{}h ago", secs / 3600)
526 } else {
527 format!("{}d ago", secs / 86400)
528 }
529}