use hx_ai::Message; use serde::{Deserialize, Serialize}; use std::io::{BufRead, Write}; use std::path::{Path, PathBuf}; #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct Entry { pub id: u64, pub parent: Option, pub message: Message, #[serde(default, skip_serializing_if = "Option::is_none")] pub model: Option, #[serde(default, skip_serializing_if = "Option::is_none")] pub usage: Option, #[serde(default, skip_serializing_if = "Option::is_none")] pub mask: Option, } pub struct Session { path: PathBuf, entries: Vec, head: Option, } impl Session { pub fn open(path: impl AsRef) -> std::io::Result { let path = path.as_ref().to_path_buf(); if let Some(d) = path.parent() { std::fs::create_dir_all(d)?; } let mut entries = vec![]; if let Ok(f) = std::fs::File::open(&path) { for l in std::io::BufReader::new(f).lines() { let l = l?; if let Ok(e) = serde_json::from_str::(&l) { entries.push(e); } } } let head = entries.last().map(|e| e.id); Ok(Self { path, entries, head, }) } pub fn path(&self) -> &Path { &self.path } pub fn head(&self) -> Option { self.head } pub fn append(&mut self, message: Message) -> std::io::Result { self.append_by(message, None) } pub fn append_by(&mut self, message: Message, model: Option) -> std::io::Result { self.append_full(message, model, None) } pub fn append_full( &mut self, message: Message, model: Option, usage: Option, ) -> std::io::Result { self.append_masked(message, model, usage, None) } pub fn append_masked( &mut self, message: Message, model: Option, usage: Option, mask: Option, ) -> std::io::Result { let id = self.entries.last().map_or(0, |e| e.id + 1); let e = Entry { id, parent: self.head, message, model, usage, mask, }; let mut f = std::fs::OpenOptions::new() .create(true) .append(true) .open(&self.path)?; writeln!( f, "{}", serde_json::to_string(&e).map_err(std::io::Error::other)? )?; self.entries.push(e); self.head = Some(id); Ok(id) } pub fn rebase(&mut self, msgs: Vec) -> std::io::Result<()> { self.head = None; for m in msgs { self.append(m)?; } Ok(()) } pub fn fork(&mut self, id: u64) -> bool { let ok = self.entries.iter().any(|e| e.id == id); if ok { self.head = Some(id); } ok } pub fn usages(&self) -> Vec<(u64, &hx_ai::Usage)> { self.entries .iter() .filter_map(|e| e.usage.as_ref().map(|u| (e.id, u))) .collect() } pub fn model_usages(&self) -> Vec<(Option<&str>, &hx_ai::Usage)> { self.entries .iter() .filter_map(|e| e.usage.as_ref().map(|u| (e.model.as_deref(), u))) .collect() } fn branch(&self) -> Vec<&Entry> { let mut out = vec![]; let mut cur = self.head; while let Some(id) = cur { let Some(e) = self.entries.iter().find(|e| e.id == id) else { break; }; out.push(e); cur = e.parent; } out.reverse(); out } pub fn messages(&self) -> Vec { self.branch() .into_iter() .map(|e| e.message.clone()) .collect() } pub fn masks(&self) -> Vec> { self.branch().into_iter().map(|e| e.mask).collect() } } pub fn dir(root: &Path, cwd: &Path, host: Option<&str>) -> PathBuf { let cwd = cwd.to_string_lossy(); let slug: String = host .into_iter() .chain([cwd.trim_matches('/')]) .collect::>() .join("/") .chars() .map(|c| if c.is_ascii_alphanumeric() { c } else { '-' }) .collect(); root.join(slug.trim_matches('-')) } pub fn new_path(dir: &Path) -> PathBuf { let ts = std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) .unwrap_or_default() .as_millis(); let mut p = dir.join(format!("{ts}.jsonl")); let mut n = 0; while p.exists() { n += 1; p = dir.join(format!("{ts}-{n}.jsonl")); } p } #[derive(Debug, Clone, PartialEq)] pub struct Meta { pub path: PathBuf, pub title: String, pub modified: std::time::SystemTime, pub messages: usize, pub model: Option, pub branches: usize, pub project: String, } pub const UNTITLED: &str = "(untitled)"; pub fn title(msgs: &[Message]) -> Option { msgs.iter() .filter(|m| m.role == hx_ai::Role::User) .map(|m| m.text()) .find(|t| !t.trim().is_empty()) .map(|t| { t.trim() .lines() .next() .unwrap_or_default() .chars() .take(80) .collect() }) } impl Session { pub fn meta(&self) -> Meta { let all: Vec = self.entries.iter().map(|e| e.message.clone()).collect(); let parents: std::collections::HashSet = self.entries.iter().filter_map(|e| e.parent).collect(); Meta { path: self.path.clone(), title: title(&all).unwrap_or_else(|| UNTITLED.into()), modified: std::fs::metadata(&self.path) .and_then(|m| m.modified()) .unwrap_or(std::time::UNIX_EPOCH), messages: self.messages().len(), model: self.entries.iter().rev().find_map(|e| e.model.clone()), branches: self .entries .iter() .filter(|e| !parents.contains(&e.id)) .count(), project: self .path .parent() .and_then(|d| d.file_name()) .map(|n| n.to_string_lossy().into_owned()) .unwrap_or_default(), } } } pub fn list(dir: &Path) -> Vec { let mut v: Vec = std::fs::read_dir(dir) .into_iter() .flatten() .flatten() .map(|e| e.path()) .filter(|p| p.extension().is_some_and(|x| x == "jsonl")) .filter_map(|p| Session::open(&p).ok()) .filter(|s| !s.entries.is_empty()) .map(|s| s.meta()) .collect(); v.sort_by(|a, b| (b.modified, &b.path).cmp(&(a.modified, &a.path))); v } pub fn list_all(root: &Path) -> Vec { let mut v: Vec = std::fs::read_dir(root) .into_iter() .flatten() .flatten() .filter(|e| e.path().is_dir()) .flat_map(|e| list(&e.path())) .collect(); v.sort_by(|a, b| (b.modified, &b.path).cmp(&(a.modified, &a.path))); v } #[cfg(test)] mod tests { use super::*; #[test] fn branch_and_resume() { let d = tempfile::tempdir().unwrap(); let p = d.path().join("s/a.jsonl"); let mut s = Session::open(&p).unwrap(); let a = s.append(Message::user("a")).unwrap(); s.append(Message::user("b")).unwrap(); assert!(s.fork(a)); s.append(Message::user("c")).unwrap(); let txt = |s: &Session| s.messages().iter().map(|m| m.text()).collect::>(); assert_eq!(txt(&s), ["a", "c"]); std::fs::OpenOptions::new() .append(true) .open(&p) .unwrap() .write_all(b"{torn") .unwrap(); let s2 = Session::open(&p).unwrap(); assert_eq!(txt(&s2), ["a", "c"]); assert!(!Session::open(&p).unwrap().fork(99)); } #[test] fn listing() { let d = tempfile::tempdir().unwrap(); let proj = d.path().join("sessions/proj"); let mut a = Session::open(proj.join("1.jsonl")).unwrap(); a.append(Message { role: hx_ai::Role::User, content: vec![hx_ai::ContentBlock::ToolResult { tool_use_id: "x".into(), content: "r".into(), is_error: false, }], }) .unwrap(); let root = a.append(Message::user(" fix parser\nmore")).unwrap(); a.append_by( Message { role: hx_ai::Role::Assistant, content: vec![hx_ai::ContentBlock::Text { text: "ok".into() }], }, Some("opus".into()), ) .unwrap(); a.fork(root); a.append(Message::user("other")).unwrap(); std::fs::write(proj.join("empty.jsonl"), "").unwrap(); std::thread::sleep(std::time::Duration::from_millis(20)); let mut b = Session::open(d.path().join("sessions/other/2.jsonl")).unwrap(); b.append(Message::user("newer")).unwrap(); std::fs::OpenOptions::new() .append(true) .open(b.path()) .unwrap() .write_all(b"{torn") .unwrap(); let l = list(&proj); assert_eq!(l.len(), 1, "empty file skipped"); let m = &l[0]; assert_eq!(m.title, "fix parser"); assert_eq!((m.messages, m.branches), (3, 2)); assert_eq!(m.model.as_deref(), Some("opus")); assert_eq!(m.project, "proj"); let all = list_all(&d.path().join("sessions")); let t: Vec<_> = all .iter() .map(|m| (m.title.as_str(), m.project.as_str())) .collect(); assert_eq!(t, [("newer", "other"), ("fix parser", "proj")]); assert_eq!( dir(Path::new("/h"), Path::new("/a/b c"), None), Path::new("/h/a-b-c") ); assert_eq!( dir(Path::new("/h"), Path::new("/a/b"), Some("box")), Path::new("/h/box-a-b") ); let n = new_path(&proj); assert!(n.starts_with(&proj) && !n.exists()); assert!( serde_json::from_str::( r#"{"id":0,"parent":null,"message":{"role":"user","content":[]}}"# ) .is_ok() ); } }