M10: /new, session listing, /sessions picker, hx -r, session titles, rpc session ops
ci / check (push) Canceled after 0s
ci / check (pull_request) Canceled after 0s

Closes #86, closes #87, closes #88, closes #89, closes #90, closes #91
This commit is contained in:
hermes committed 2026-10-01 09:35:47 +00:00
1 parent 1e87857a34
commit 23eb00d920
12 files changed
+957 -124

No files matched your search

+2 -1
View File
@@ -174,7 +174,8 @@ impl Agent {
}
fn push(&mut self, m: Message) -> Result<(), Error> {
self.session.append(m.clone())?;
let by = (m.role == Role::Assistant).then(|| self.model.clone());
self.session.append_by(m, by)?;
Ok(())
}
+4 -2
View File
@@ -57,12 +57,14 @@ pub fn builtins(models: &[&str]) -> Vec<CmdSpec> {
Enum(vec!["claude".into(), "codex".into()]),
),
b("compact", "summarize old context", None),
b("clear", "start an empty session", None),
b("new", "start a new session (old one stays resumable)", None),
b("clear", "alias of /new", None),
b("sessions", "browse, resume, delete sessions", None),
b("lsp", "language server status", None),
b("skills", "list skills and where they load from", None),
b(
"resume",
"switch to a session file (ctrl-p lists recent)",
"resume a session file; no arg opens /sessions",
Path,
),
b("quit", "exit hx", None),
+194
View File
@@ -11,6 +11,9 @@ pub struct Entry {
pub id: u64,
pub parent: Option<u64>,
pub message: Message,
/// Model that produced an assistant message (absent in older files).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub model: Option<String>,
}
pub struct Session {
@@ -52,11 +55,17 @@ impl Session {
}
pub fn append(&mut self, message: Message) -> std::io::Result<u64> {
self.append_by(message, None)
}
/// Append, recording which model produced it.
pub fn append_by(&mut self, message: Message, model: Option<String>) -> std::io::Result<u64> {
let id = self.entries.last().map_or(0, |e| e.id + 1);
let e = Entry {
id,
parent: self.head,
message,
model,
};
let mut f = std::fs::OpenOptions::new()
.create(true)
@@ -106,6 +115,126 @@ impl Session {
}
}
/// `<hx home>/sessions/<slug of cwd>`.
pub fn dir(home: &Path, cwd: &Path) -> PathBuf {
let slug: String = cwd
.to_string_lossy()
.chars()
.map(|c| if c.is_ascii_alphanumeric() { c } else { '-' })
.collect();
home.join("sessions").join(slug.trim_matches('-'))
}
/// A fresh, not yet created session file in `dir` (created on first append).
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,
/// First line of the first user prompt; "(untitled)" when there is none.
pub title: String,
pub modified: std::time::SystemTime,
/// Messages on the head path.
pub messages: usize,
/// Model of the last assistant entry that recorded one.
pub model: Option<String>,
/// Leaf entries: >1 means forks or compactions.
pub branches: usize,
/// Session dir name (project slug).
pub project: String,
}
pub const UNTITLED: &str = "(untitled)";
/// Title of a conversation: first line of the first user text, ≤80 chars.
pub fn title(msgs: &[Message]) -> Option<String> {
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<Message> = self.entries.iter().map(|e| e.message.clone()).collect();
let parents: std::collections::HashSet<u64> =
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(),
}
}
}
/// Sessions in `dir`, newest first. Empty files are skipped.
// ponytail: parses every file on each call; fine for hundreds of sessions, add an index beyond that.
pub fn list(dir: &Path) -> Vec<Meta> {
let mut v: Vec<Meta> = 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();
// equal mtimes (coarse clocks): newer timestamped file name wins
v.sort_by(|a, b| (b.modified, &b.path).cmp(&(a.modified, &a.path)));
v
}
/// Sessions of every project under `<hx home>/sessions`, newest first.
pub fn list_all(root: &Path) -> Vec<Meta> {
let mut v: Vec<Meta> = std::fs::read_dir(root)
.into_iter()
.flatten()
.flatten()
.filter(|e| e.path().is_dir())
.flat_map(|e| list(&e.path()))
.collect();
// equal mtimes (coarse clocks): newer timestamped file name wins
v.sort_by(|a, b| (b.modified, &b.path).cmp(&(a.modified, &a.path)));
v
}
#[cfg(test)]
mod tests {
use super::*;
@@ -131,4 +260,69 @@ mod tests {
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();
// first user message is only a tool result: title comes from the next prompt
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")),
Path::new("/h/sessions/a-b-c")
);
let n = new_path(&proj);
assert!(n.starts_with(&proj) && !n.exists());
// old files without `model` still load
assert!(
serde_json::from_str::<Entry>(
r#"{"id":0,"parent":null,"message":{"role":"user","content":[]}}"#
)
.is_ok()
);
}
}