Skip to main content

tinyharness_lib/
session.rs

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// ── Data types ──────────────────────────────────────────────────────────────
15
16/// Metadata about a session, stored as the first line of the JSONL file.
17#[derive(Debug, Clone, Serialize, Deserialize)]
18pub struct SessionMeta {
19    /// Unique session identifier (UUID v4).
20    pub id: String,
21    /// Working directory when the session was created.
22    pub working_dir: String,
23    /// Unix timestamp (seconds) when the session was created.
24    pub created_at: u64,
25    /// Unix timestamp (seconds) when the session was last updated.
26    pub updated_at: u64,
27    /// The agent mode used in this session.
28    pub mode: AgentMode,
29    /// The provider kind (e.g. "ollama", "llama.cpp", "vllm").
30    pub provider: String,
31    /// The model name.
32    pub model: Option<String>,
33    /// Optional user-defined name for the session.
34    pub name: Option<String>,
35    /// Number of messages in the session.
36    pub message_count: usize,
37    /// Last known token usage reported by the LLM provider.
38    /// This is the prompt token count at the time of the last
39    /// provider response, serialized so it survives restarts.
40    #[serde(default)]
41    pub token_usage: Option<TokenUsage>,
42    /// Cumulative tool calls made during this session (across all turns).
43    #[serde(default)]
44    pub total_tool_calls: u64,
45    /// Cumulative total tokens consumed across all LLM calls in this session.
46    #[serde(default)]
47    pub total_tokens_used: u64,
48}
49
50/// A single line in the session JSONL file.
51#[derive(Debug, Clone, Serialize, Deserialize)]
52#[serde(tag = "type")]
53pub enum SessionEntry {
54    /// First entry: session metadata.
55    #[serde(rename = "meta")]
56    Meta(SessionMeta),
57    /// A conversation message.
58    #[serde(rename = "message")]
59    Message(Message),
60}
61
62// ── Error type ──────────────────────────────────────────────────────────────
63
64/// Error type for session I/O operations.
65#[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
104// ── Session store ───────────────────────────────────────────────────────────
105
106/// Handles persistence of sessions as JSONL files in a directory.
107///
108/// By default, uses `~/.local/share/tinyharness/sessions/`. This can be
109/// overridden with [`SessionStore::new`] for testing or alternative paths.
110pub struct SessionStore {
111    dir: PathBuf,
112}
113
114impl SessionStore {
115    /// Create a store that uses the default session directory
116    /// (`~/.local/share/tinyharness/sessions/`).
117    ///
118    /// Prefer [`SessionStore::from_paths`] when the caller has a
119    /// [`Paths`](crate::paths::Paths) instance — this form resolves from the
120    /// ambient process environment.
121    pub fn default_path() -> Self {
122        Self::from_paths(&crate::paths::Paths::default())
123    }
124
125    /// Create a store that uses `paths.sessions_dir()`.
126    pub fn from_paths(paths: &crate::paths::Paths) -> Self {
127        SessionStore {
128            dir: paths.sessions_dir(),
129        }
130    }
131
132    /// Create a store that uses a custom directory.
133    pub fn new(dir: PathBuf) -> Self {
134        SessionStore { dir }
135    }
136
137    /// Ensure the session directory exists.
138    pub fn ensure_dir(&self) -> Result<(), SessionError> {
139        fs::create_dir_all(&self.dir)?;
140        Ok(())
141    }
142
143    /// Create a brand-new session and write its initial metadata to disk.
144    /// Returns the new `Session` handle.
145    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        // Eagerly create the session file so callers get immediate feedback on errors
176        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    /// Load an existing session by its full ID.
188    /// Returns the session handle and the conversation messages.
189    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                    // Skip malformed lines rather than failing
220                }
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    /// Find the most recent session for a given working directory.
240    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    /// Find a session by an ID prefix.
275    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    /// List all sessions, most recently updated first.
300    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    /// Returns the directory path where sessions are stored.
325    pub fn dir(&self) -> &PathBuf {
326        &self.dir
327    }
328
329    /// Delete a session by its ID.
330    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
345// ── Helpers ──────────────────────────────────────────────────────────────────
346
347fn 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
368// ── Session handle ─────────────────────────────────────────────────────────
369
370/// Manages a session's lifecycle: writing entries to the JSONL file.
371///
372/// Use [`SessionStore`] to create or load sessions. The `Session` type
373/// handles the actual message appending, metadata updates, and auto-save.
374pub struct Session {
375    meta: SessionMeta,
376    path: PathBuf,
377    dirty: bool,
378    messages_since_save: usize,
379    created: bool,
380}
381
382/// Auto-save threshold: flush metadata every N messages appended.
383const AUTO_SAVE_INTERVAL: usize = 5;
384
385impl Session {
386    // ── Mutating operations ────────────────────────────────────────────
387
388    /// Append a message to the session file and update metadata.
389    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    /// Update the session mode.
403    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    /// Update the model name.
410    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    /// Set a human-readable name for the session.
417    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    /// Set the last known token usage reported by the provider.
424    /// This is stored in the session metadata so it survives restarts.
425    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    /// Add to the cumulative tool call count for this session.
432    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    /// Add to the cumulative total tokens used in this session.
439    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    /// Flush any metadata changes back to the file (rewrite the first line).
446    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    // ── Accessors ──────────────────────────────────────────────────────
498
499    pub fn id(&self) -> &str {
500        &self.meta.id
501    }
502
503    /// Full path to the session's JSONL file.
504    pub fn path(&self) -> &Path {
505        &self.path
506    }
507
508    pub fn meta(&self) -> &SessionMeta {
509        &self.meta
510    }
511
512    // ── Internal ────────────────────────────────────────────────────────
513
514    fn ensure_created(&mut self) {
515        if self.created {
516            return;
517        }
518
519        // Ensure directory exists
520        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
554/// Format a duration in seconds as a human-friendly age string.
555pub 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}