M10: /new, session listing, /sessions picker, hx -r, session titles, rpc session ops
Closes #86, closes #87, closes #88, closes #89, closes #90, closes #91
This commit is contained in:
1 parent
1e87857a34
commit
23eb00d920
12 files changed
+957
-124
No files matched your search
+26
-20
@@ -31,6 +31,9 @@ struct Cli {
|
||||
/// Continue the most recent session in this directory.
|
||||
#[arg(short, long)]
|
||||
r#continue: bool,
|
||||
/// Resume: no value opens the session picker; with a query resumes the best title match.
|
||||
#[arg(short, long, num_args = 0..=1, default_missing_value = "")]
|
||||
resume: Option<String>,
|
||||
/// Output mode: text (default for -p), json (NDJSON events on stdout; needs -p), rpc (JSON-RPC on stdio).
|
||||
#[arg(long, value_enum, default_value_t = Mode::Text)]
|
||||
mode: Mode,
|
||||
@@ -235,14 +238,7 @@ impl<H: Hook> Hook for ArcHook<H> {
|
||||
}
|
||||
|
||||
fn session_dir(cwd: &std::path::Path) -> std::path::PathBuf {
|
||||
let slug: String = cwd
|
||||
.to_string_lossy()
|
||||
.chars()
|
||||
.map(|c| if c.is_ascii_alphanumeric() { c } else { '-' })
|
||||
.collect();
|
||||
context::hx_home()
|
||||
.join("sessions")
|
||||
.join(slug.trim_matches('-'))
|
||||
hx_core::session::dir(&context::hx_home(), cwd)
|
||||
}
|
||||
|
||||
#[tokio::main]
|
||||
@@ -302,19 +298,28 @@ async fn main() -> Result<()> {
|
||||
.unwrap_or_else(|| default_model(kind))
|
||||
});
|
||||
let dir = session_dir(&cwd);
|
||||
let path = match (cli.session, cli.r#continue) {
|
||||
(Some(p), _) => p,
|
||||
(None, true) => std::fs::read_dir(&dir)
|
||||
.ok()
|
||||
.and_then(|rd| rd.flatten().map(|e| e.path()).max())
|
||||
.ok_or_else(|| anyhow::anyhow!("no previous session in {}", dir.display()))?,
|
||||
(None, false) => {
|
||||
let ts = std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)?
|
||||
.as_millis();
|
||||
dir.join(format!("{ts}.jsonl"))
|
||||
let query = cli.resume.as_deref().filter(|q| !q.is_empty());
|
||||
let path = match (cli.session, cli.r#continue, query) {
|
||||
(Some(p), _, _) => p,
|
||||
(None, _, Some(q)) => {
|
||||
let all = hx_core::session::list(&dir);
|
||||
let titles: Vec<&str> = all.iter().map(|m| m.title.as_str()).collect();
|
||||
let best = hx_core::command::rank(titles.iter().copied(), q, 1);
|
||||
let m = best
|
||||
.first()
|
||||
.and_then(|t| all.iter().find(|m| m.title == *t))
|
||||
.ok_or_else(|| anyhow::anyhow!("no session in {} matches {q:?}", dir.display()))?;
|
||||
eprintln!("[resuming: {}]", m.title);
|
||||
m.path.clone()
|
||||
}
|
||||
(None, true, None) => hx_core::session::list(&dir)
|
||||
.into_iter()
|
||||
.next()
|
||||
.map(|m| m.path)
|
||||
.ok_or_else(|| anyhow::anyhow!("no previous session in {}", dir.display()))?,
|
||||
(None, false, None) => hx_core::session::new_path(&dir),
|
||||
};
|
||||
let open_sessions = cli.resume.as_deref() == Some("");
|
||||
let cx = ToolCtx {
|
||||
cwd: cwd.clone(),
|
||||
state: Default::default(),
|
||||
@@ -413,7 +418,7 @@ async fn main() -> Result<()> {
|
||||
}
|
||||
let specs = command_specs(&mcp, &cwd);
|
||||
if cli.mode == Mode::Rpc {
|
||||
let r = rpc::serve(agent, abort, specs, hx_tui::project_files(&cwd)).await;
|
||||
let r = rpc::serve(agent, abort, specs, hx_tui::project_files(&cwd), dir).await;
|
||||
mgr.shutdown().await;
|
||||
return r;
|
||||
}
|
||||
@@ -428,6 +433,7 @@ async fn main() -> Result<()> {
|
||||
default_model,
|
||||
pricing,
|
||||
specs,
|
||||
open_sessions,
|
||||
commands: {
|
||||
let mcp = mcp.clone();
|
||||
Box::new(move |name: &str, arg: &str| {
|
||||
|
||||
@@ -45,12 +45,14 @@ fn reply(id: &Value, r: Result<Value, String>) {
|
||||
|
||||
/// Methods: `prompt {text}` (replies when the run ends; events stream meanwhile), `abort`,
|
||||
/// `state`, `messages`, `fork {id}`, `clear`, `set_model {model}`, `compact`,
|
||||
/// `complete {line, cursor?}` (cursor = byte offset, default end). One prompt at a time.
|
||||
/// `complete {line, cursor?}` (cursor = byte offset, default end), `sessions {scope?: project|all}`,
|
||||
/// `new`, `resume {path}`. One prompt at a time.
|
||||
pub async fn serve(
|
||||
mut agent: Agent,
|
||||
abort: AbortHandle,
|
||||
specs: Vec<hx_core::command::CmdSpec>,
|
||||
files: Vec<String>,
|
||||
session_dir: std::path::PathBuf,
|
||||
) -> Result<()> {
|
||||
agent.bus.add(Notify);
|
||||
let agent = Arc::new(Mutex::new(agent));
|
||||
@@ -119,6 +121,7 @@ pub async fn serve(
|
||||
let r = match method {
|
||||
"state" => Ok(json!({
|
||||
"model": a.model, "session": a.session.path(), "head": a.session.head(),
|
||||
"title": hx_core::session::title(&a.session.messages()),
|
||||
"messages": a.session.messages().len(), "usage": a.usage,
|
||||
"tools": a.tools.specs().into_iter().map(|t| t.name).collect::<Vec<_>>(),
|
||||
})),
|
||||
@@ -144,6 +147,33 @@ pub async fn serve(
|
||||
.await
|
||||
.map(|c| json!({"compacted": c}))
|
||||
.map_err(|e| e.to_string()),
|
||||
"sessions" => {
|
||||
use hx_core::session::{list, list_all};
|
||||
let v = match p["scope"].as_str() {
|
||||
Some("all") => list_all(session_dir.parent().unwrap_or(&session_dir)),
|
||||
_ => list(&session_dir),
|
||||
};
|
||||
Ok(json!(v.iter().map(|m| json!({
|
||||
"path": m.path, "title": m.title, "messages": m.messages, "model": m.model,
|
||||
"branches": m.branches, "project": m.project,
|
||||
"modified": m.modified.duration_since(std::time::UNIX_EPOCH).map_or(0, |d| d.as_secs()),
|
||||
})).collect::<Vec<_>>()))
|
||||
}
|
||||
"new" => hx_core::session::Session::open(hx_core::session::new_path(&session_dir))
|
||||
.map(|s| {
|
||||
a.session = s;
|
||||
json!({"session": a.session.path()})
|
||||
})
|
||||
.map_err(|e| e.to_string()),
|
||||
"resume" => match p["path"].as_str() {
|
||||
Some(path) => hx_core::session::Session::open(path)
|
||||
.map(|s| {
|
||||
a.session = s;
|
||||
json!({"session": a.session.path(), "messages": a.session.messages().len()})
|
||||
})
|
||||
.map_err(|e| e.to_string()),
|
||||
None => Err("params.path required".into()),
|
||||
},
|
||||
other => Err(format!("method not found: {other}")),
|
||||
};
|
||||
if !id.is_null() {
|
||||
|
||||
@@ -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(())
|
||||
}
|
||||
|
||||
|
||||
@@ -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),
|
||||
|
||||
@@ -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()
|
||||
);
|
||||
}
|
||||
}
|
||||
+202
-47
@@ -2,6 +2,7 @@
|
||||
|
||||
pub mod editor;
|
||||
pub mod picker;
|
||||
pub mod sessions;
|
||||
pub mod theme;
|
||||
pub mod transcript;
|
||||
|
||||
@@ -43,6 +44,8 @@ pub struct Setup {
|
||||
pub commands: Commands,
|
||||
/// Everything completable/listed by `/help`: builtins, skills, MCP prompts, extensions.
|
||||
pub specs: Vec<CmdSpec>,
|
||||
/// Open the session picker at startup (`hx -r`).
|
||||
pub open_sessions: bool,
|
||||
}
|
||||
|
||||
pub enum CmdOut {
|
||||
@@ -105,6 +108,9 @@ struct App {
|
||||
/// open completion popup and selected row
|
||||
popup: Option<(Completion, usize)>,
|
||||
picker: Option<picker::Picker>,
|
||||
sessions: Option<sessions::Sessions>,
|
||||
/// session title for footer / terminal title; None until the first prompt
|
||||
title: Option<String>,
|
||||
/// right-hand panel on wide terminals: (title, text) of the last listing / expanded output
|
||||
panel: Option<(String, String)>,
|
||||
session_path: std::path::PathBuf,
|
||||
@@ -160,6 +166,7 @@ pub async fn run(setup: Setup) -> std::io::Result<()> {
|
||||
lsp_status,
|
||||
commands,
|
||||
specs,
|
||||
open_sessions,
|
||||
} = setup;
|
||||
let (tx, mut rx) = mpsc::unbounded_channel();
|
||||
agent.bus.add(Forward(tx.clone()));
|
||||
@@ -197,12 +204,17 @@ pub async fn run(setup: Setup) -> std::io::Result<()> {
|
||||
specs,
|
||||
popup: None,
|
||||
picker: None,
|
||||
sessions: None,
|
||||
title: hx_core::session::title(&agent.session.messages()),
|
||||
panel: None,
|
||||
session_path: agent.session.path().to_path_buf(),
|
||||
wide: false,
|
||||
ask: None,
|
||||
};
|
||||
show_history(&mut app.t, &agent.session.messages());
|
||||
sessions::history(&mut app.t, &agent.session.messages());
|
||||
if open_sessions {
|
||||
open_sessions_picker(&mut app);
|
||||
}
|
||||
app.t
|
||||
.push(Item::Info(format!("hx · {:?} · {}", app.kind, app.model)));
|
||||
let agent = Arc::new(Mutex::new(agent));
|
||||
@@ -220,8 +232,16 @@ pub async fn run(setup: Setup) -> std::io::Result<()> {
|
||||
let mut keys = EventStream::new();
|
||||
let mut tick = tokio::time::interval(std::time::Duration::from_millis(50));
|
||||
let mut dirty = true;
|
||||
let mut last_title = String::new();
|
||||
while !app.quit {
|
||||
if std::mem::take(&mut dirty) {
|
||||
let t = format!("hx · {}", app.title.as_deref().unwrap_or("new session"));
|
||||
if t != last_title {
|
||||
// OSC 2: terminal window title
|
||||
use std::io::Write;
|
||||
let _ = write!(std::io::stdout(), "\x1b]2;{t}\x07");
|
||||
last_title = t;
|
||||
}
|
||||
term.draw(|f| draw(f, &mut app))?;
|
||||
}
|
||||
tokio::select! {
|
||||
@@ -301,23 +321,6 @@ pub async fn run(setup: Setup) -> std::io::Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Text of user/assistant messages, for a resumed session.
|
||||
fn show_history(t: &mut Transcript, msgs: &[hx_ai::Message]) {
|
||||
for m in msgs {
|
||||
for b in &m.content {
|
||||
match (m.role, b) {
|
||||
(hx_ai::Role::User, hx_ai::ContentBlock::Text { text }) => {
|
||||
t.push(Item::User(text.clone()))
|
||||
}
|
||||
(hx_ai::Role::Assistant, hx_ai::ContentBlock::Text { text }) => {
|
||||
t.push(Item::Assistant(text.clone()))
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Sessions live next to the current one.
|
||||
fn sessions_dir(app: &App) -> &std::path::Path {
|
||||
app.session_path
|
||||
@@ -325,6 +328,40 @@ fn sessions_dir(app: &App) -> &std::path::Path {
|
||||
.unwrap_or(std::path::Path::new("."))
|
||||
}
|
||||
|
||||
fn open_sessions_picker(app: &mut App) {
|
||||
let dir = sessions_dir(app).to_path_buf();
|
||||
let root = dir.parent().unwrap_or(&dir).to_path_buf();
|
||||
app.picker = None;
|
||||
app.popup = None;
|
||||
app.sessions = Some(sessions::Sessions::new(&dir, &root, &app.session_path));
|
||||
}
|
||||
|
||||
/// Session picker keys. Returns `/resume <path>` to submit on enter.
|
||||
fn sessions_key(app: &mut App, k: KeyEvent) -> Option<String> {
|
||||
match app.sessions.as_mut()?.key(k) {
|
||||
sessions::Act::None => None,
|
||||
sessions::Act::Close => {
|
||||
app.sessions = None;
|
||||
None
|
||||
}
|
||||
sessions::Act::Resume(p) => {
|
||||
app.sessions = None;
|
||||
(p != app.session_path).then(|| format!("/resume {}", p.display()))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Replace the agent's session (resume or new) and rebuild the transcript.
|
||||
fn switch_session(app: &mut App, a: &mut Agent, sess: hx_core::session::Session) {
|
||||
app.t = Transcript::default();
|
||||
let msgs = sess.messages();
|
||||
sessions::history(&mut app.t, &msgs);
|
||||
app.ctx_tokens = hx_core::agent::estimate_tokens(&msgs);
|
||||
app.title = hx_core::session::title(&msgs);
|
||||
app.session_path = sess.path().to_path_buf();
|
||||
a.session = sess;
|
||||
}
|
||||
|
||||
/// Picker keys. Returns a line to submit when an entry runs.
|
||||
fn picker_key(app: &mut App, k: KeyEvent) -> Option<String> {
|
||||
let p = app.picker.as_mut()?;
|
||||
@@ -375,6 +412,9 @@ fn on_key(app: &mut App, k: KeyEvent, abort: &AbortHandle) -> Option<String> {
|
||||
let alt = k.modifiers.contains(KeyModifiers::ALT);
|
||||
let shift = k.modifiers.contains(KeyModifiers::SHIFT);
|
||||
app.hint.clear();
|
||||
if app.sessions.is_some() {
|
||||
return sessions_key(app, k);
|
||||
}
|
||||
if app.picker.is_some() {
|
||||
return picker_key(app, k);
|
||||
}
|
||||
@@ -566,16 +606,22 @@ async fn submit(app: &mut App, mut line: String, c: &Ctx<'_>) {
|
||||
}
|
||||
"resume" if !arg.is_empty() => match hx_core::session::Session::open(arg) {
|
||||
Ok(sess) => {
|
||||
let mut a = agent.lock().await;
|
||||
app.t = Transcript::default();
|
||||
show_history(&mut app.t, &sess.messages());
|
||||
app.ctx_tokens = hx_core::agent::estimate_tokens(&sess.messages());
|
||||
app.session_path = sess.path().to_path_buf();
|
||||
a.session = sess;
|
||||
switch_session(app, &mut *agent.lock().await, sess);
|
||||
app.t.push(Item::Info(format!("resumed {arg}")));
|
||||
}
|
||||
Err(e) => app.t.push(Item::Error(format!("/resume: {e}"))),
|
||||
},
|
||||
"sessions" | "resume" => open_sessions_picker(app),
|
||||
"new" | "clear" => {
|
||||
let p = hx_core::session::new_path(sessions_dir(app));
|
||||
match hx_core::session::Session::open(&p) {
|
||||
Ok(sess) => {
|
||||
switch_session(app, &mut *agent.lock().await, sess);
|
||||
app.t.push(Item::Info("new session".into()));
|
||||
}
|
||||
Err(e) => app.t.push(Item::Error(format!("/new: {e}"))),
|
||||
}
|
||||
}
|
||||
"model" if arg.is_empty() => app.t.push(Item::Info(format!("model: {}", app.model))),
|
||||
"model" => {
|
||||
agent.lock().await.model = arg.into();
|
||||
@@ -613,13 +659,6 @@ async fn submit(app: &mut App, mut line: String, c: &Ctx<'_>) {
|
||||
let _ = tx.send(Ui::Compacted(r));
|
||||
});
|
||||
}
|
||||
"clear" => {
|
||||
let mut a = agent.lock().await;
|
||||
let _ = a.session.rebase(vec![]);
|
||||
app.t = Transcript::default();
|
||||
app.ctx_tokens = 0;
|
||||
app.t.push(Item::Info("cleared".into()));
|
||||
}
|
||||
_ if let Some(Source::Skill(p)) =
|
||||
app.specs.iter().find(|s| s.name == c).map(|s| &s.source) =>
|
||||
{
|
||||
@@ -652,6 +691,9 @@ async fn submit(app: &mut App, mut line: String, c: &Ctx<'_>) {
|
||||
return;
|
||||
}
|
||||
// a command that expanded into a prompt shows as typed
|
||||
if app.title.is_none() {
|
||||
app.title = hx_core::session::title(&[hx_ai::Message::user(shown.clone())]);
|
||||
}
|
||||
app.t.push(Item::User(if shown.starts_with('/') {
|
||||
shown
|
||||
} else {
|
||||
@@ -751,6 +793,9 @@ fn draw(f: &mut ratatui::Frame, app: &mut App) {
|
||||
if let Some(p) = &app.picker {
|
||||
p.draw(f);
|
||||
}
|
||||
if let Some(s) = &mut app.sessions {
|
||||
s.draw(f);
|
||||
}
|
||||
}
|
||||
|
||||
/// `ctx ▰▰▰▱▱▱▱▱▱▱ 41k/150k · 12.3k↑ 2.1k↓ ~$0.08` left, `Claude · model · 1 queued` right.
|
||||
@@ -794,24 +839,46 @@ fn footer(app: &App, width: u16) -> Line<'static> {
|
||||
th.dim(),
|
||||
),
|
||||
];
|
||||
let right = if app.hint.is_empty() {
|
||||
let mut v = vec![format!("{:?}", app.kind), app.model.clone()];
|
||||
if !app.queue.is_empty() {
|
||||
v.push(format!("{} queued", app.queue.len()));
|
||||
}
|
||||
if app.scroll > 0 {
|
||||
v.push(format!("↑{}", app.scroll));
|
||||
}
|
||||
Span::styled(v.join(" · "), th.dim())
|
||||
} else {
|
||||
Span::styled(app.hint.clone(), th.accent())
|
||||
};
|
||||
let w = width as usize;
|
||||
let lw = |l: &[Span]| l.iter().map(Span::width).sum::<usize>();
|
||||
// narrow terminals: drop token counts, then the whole left side
|
||||
if lw(&left) + right.width() + 1 > w {
|
||||
left.pop();
|
||||
if !app.hint.is_empty() {
|
||||
let right = Span::styled(app.hint.clone(), th.accent());
|
||||
if lw(&left) + right.width() + 1 > w {
|
||||
return Line::from(right);
|
||||
}
|
||||
let pad = w - lw(&left) - right.width();
|
||||
left.push(Span::raw(" ".repeat(pad)));
|
||||
left.push(right);
|
||||
return Line::from(left);
|
||||
}
|
||||
let mut tail = vec![format!("{:?}", app.kind), app.model.clone()];
|
||||
if !app.queue.is_empty() {
|
||||
tail.push(format!("{} queued", app.queue.len()));
|
||||
}
|
||||
if app.scroll > 0 {
|
||||
tail.push(format!("↑{}", app.scroll));
|
||||
}
|
||||
let title = app.title.as_deref().unwrap_or("new session");
|
||||
// drop in order until it fits: token counts, title, context bar
|
||||
let mut title_room = w.saturating_sub(lw(&left) + tail.join(" · ").chars().count() + 4);
|
||||
if title_room < 12 {
|
||||
left.pop();
|
||||
title_room = w.saturating_sub(lw(&left) + tail.join(" · ").chars().count() + 4);
|
||||
}
|
||||
let mut right = tail.join(" · ");
|
||||
if title_room >= 12 {
|
||||
let t: String = if title.chars().count() > title_room.min(40) {
|
||||
title
|
||||
.chars()
|
||||
.take(title_room.min(40) - 1)
|
||||
.chain(['…'])
|
||||
.collect()
|
||||
} else {
|
||||
title.into()
|
||||
};
|
||||
right = format!("{t} · {right}");
|
||||
}
|
||||
let right = Span::styled(right, th.dim());
|
||||
if lw(&left) + right.width() + 1 > w {
|
||||
return Line::from(right);
|
||||
}
|
||||
@@ -921,6 +988,8 @@ mod tests {
|
||||
specs: vec![],
|
||||
popup: None,
|
||||
picker: None,
|
||||
sessions: None,
|
||||
title: None,
|
||||
panel: None,
|
||||
session_path: "/nonexistent/s.jsonl".into(),
|
||||
wide: false,
|
||||
@@ -972,6 +1041,8 @@ mod tests {
|
||||
specs: cmd::builtins(&["sonnet", "opus"]),
|
||||
popup: None,
|
||||
picker: None,
|
||||
sessions: None,
|
||||
title: None,
|
||||
panel: None,
|
||||
session_path: "/nonexistent/s.jsonl".into(),
|
||||
wide: false,
|
||||
@@ -1021,7 +1092,7 @@ mod tests {
|
||||
.map(|y| (0..40).map(|x| buf[(x, y)].symbol().to_string()).collect())
|
||||
.collect();
|
||||
assert_eq!(
|
||||
rows[3], " │ /clear start an empty session │ ",
|
||||
rows[3], " │ /clear alias of /new │ ",
|
||||
"{rows:#?}"
|
||||
);
|
||||
assert!(rows[4].starts_with(" │ /compact summarize"), "{rows:#?}");
|
||||
@@ -1038,6 +1109,22 @@ mod tests {
|
||||
"{last}"
|
||||
);
|
||||
app.hint.clear();
|
||||
let mut foot = |app: &mut App| {
|
||||
term.draw(|f| draw(f, app)).unwrap();
|
||||
let buf = term.backend().buffer().clone();
|
||||
(0..100)
|
||||
.map(|x| buf[(x, 9)].symbol().to_string())
|
||||
.collect::<String>()
|
||||
};
|
||||
assert!(foot(&mut app).ends_with("new session · Claude · m1"));
|
||||
app.title = Some("fix the flaky rust-analyzer test".into());
|
||||
let last = foot(&mut app);
|
||||
assert!(
|
||||
last.starts_with("ctx ▱")
|
||||
&& last.ends_with("fix the flaky rust-analyzer test · Claude · m1"),
|
||||
"{last}"
|
||||
);
|
||||
app.title = None;
|
||||
key(&mut app, KeyCode::Down);
|
||||
key(&mut app, KeyCode::Up);
|
||||
key(&mut app, KeyCode::Up);
|
||||
@@ -1137,4 +1224,72 @@ mod tests {
|
||||
show(&mut app, "skills", "x".into());
|
||||
assert_eq!(app.t.items, [Item::Info("x".into())]);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn new_session_keeps_old_file() {
|
||||
let t = tempfile::tempdir().unwrap();
|
||||
let old = t.path().join("1.jsonl");
|
||||
let mut s = hx_core::session::Session::open(&old).unwrap();
|
||||
s.append(hx_ai::Message::user("first")).unwrap();
|
||||
let before = std::fs::read_to_string(&old).unwrap();
|
||||
let (agent, _) = Agent::new(
|
||||
Arc::new(NoProvider),
|
||||
Default::default(),
|
||||
hx_core::session::Session::open(&old).unwrap(),
|
||||
hx_core::tool::ToolCtx {
|
||||
cwd: t.path().into(),
|
||||
state: Default::default(),
|
||||
},
|
||||
);
|
||||
let agent = Arc::new(Mutex::new(agent));
|
||||
let (tx, _rx) = mpsc::unbounded_channel();
|
||||
let mp: MakeProvider = Box::new(|_| Ok(Arc::new(NoProvider)));
|
||||
let ls: LspStatus = Box::new(|| Box::pin(async { vec![] }));
|
||||
let cmds: Commands = Box::new(|_, _| None);
|
||||
let ctx = Ctx {
|
||||
agent: &agent,
|
||||
tx: &tx,
|
||||
make_provider: &mp,
|
||||
default_model: |_| String::new(),
|
||||
cwd: t.path(),
|
||||
lsp_status: &ls,
|
||||
commands: &cmds,
|
||||
};
|
||||
let mut app = test_app();
|
||||
app.session_path = old.clone();
|
||||
app.title = Some("first".into());
|
||||
submit(&mut app, "/clear".into(), &ctx).await;
|
||||
let new = agent.lock().await.session.path().to_path_buf();
|
||||
assert_ne!(new, old);
|
||||
assert_eq!((new.parent(), app.title.as_deref()), (old.parent(), None));
|
||||
assert_eq!(
|
||||
std::fs::read_to_string(&old).unwrap(),
|
||||
before,
|
||||
"old file untouched"
|
||||
);
|
||||
agent
|
||||
.lock()
|
||||
.await
|
||||
.session
|
||||
.append(hx_ai::Message::user("second"))
|
||||
.unwrap();
|
||||
let l = hx_core::session::list(t.path());
|
||||
assert_eq!(l.len(), 2);
|
||||
assert_eq!(l[0].path, new, "newest first, so `hx -c` picks it");
|
||||
submit(&mut app, format!("/resume {}", old.display()), &ctx).await;
|
||||
assert_eq!(agent.lock().await.session.path(), old);
|
||||
assert_eq!(app.title.as_deref(), Some("first"));
|
||||
}
|
||||
|
||||
struct NoProvider;
|
||||
#[async_trait::async_trait]
|
||||
impl Provider for NoProvider {
|
||||
async fn stream(
|
||||
&self,
|
||||
_: hx_ai::Request,
|
||||
) -> hx_ai::Result<futures::stream::BoxStream<'static, hx_ai::Result<hx_ai::StreamEvent>>>
|
||||
{
|
||||
unimplemented!()
|
||||
}
|
||||
}
|
||||
}
|
||||
+19
-50
@@ -5,8 +5,7 @@ use hx_core::command::{self as cmd, ArgKind, CmdSpec, Source};
|
||||
use ratatui::layout::Rect;
|
||||
use ratatui::text::{Line, Span};
|
||||
use ratatui::widgets::{Block, Clear, Paragraph};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::time::SystemTime;
|
||||
use std::path::Path;
|
||||
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub enum Pick {
|
||||
@@ -30,7 +29,7 @@ pub struct Picker {
|
||||
all: Vec<Entry>,
|
||||
}
|
||||
|
||||
const SESSIONS: usize = 50;
|
||||
const SESSIONS: usize = 5;
|
||||
|
||||
impl Picker {
|
||||
pub fn new(specs: &[CmdSpec], sessions_dir: &Path, current: &Path) -> Self {
|
||||
@@ -133,59 +132,29 @@ impl Picker {
|
||||
}
|
||||
}
|
||||
|
||||
/// Recent sessions in `dir` (newest first, current one skipped): label = age, detail = first prompt.
|
||||
/// Five newest sessions in `dir` (current one skipped) plus an entry opening `/sessions`.
|
||||
fn sessions(dir: &Path, current: &Path) -> Vec<Entry> {
|
||||
let mut v: Vec<(SystemTime, PathBuf)> = std::fs::read_dir(dir)
|
||||
let all: Vec<_> = hx_core::session::list(dir)
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.flatten()
|
||||
.map(|e| e.path())
|
||||
.filter(|p| p.extension().is_some_and(|x| x == "jsonl") && p != current)
|
||||
.filter_map(|p| Some((std::fs::metadata(&p).ok()?.modified().ok()?, p)))
|
||||
.filter(|m| m.path != current)
|
||||
.collect();
|
||||
v.sort_by_key(|a| std::cmp::Reverse(a.0));
|
||||
v.into_iter()
|
||||
let mut v: Vec<Entry> = all
|
||||
.iter()
|
||||
.take(SESSIONS)
|
||||
.filter_map(|(t, p)| {
|
||||
let first = first_prompt(&p)?;
|
||||
Some(Entry {
|
||||
label: format!("session {}", ago(t)),
|
||||
detail: first,
|
||||
pick: Pick::Run(format!("/resume {}", p.display())),
|
||||
})
|
||||
.map(|m| Entry {
|
||||
label: format!("session {}", crate::sessions::ago(m.modified)),
|
||||
detail: m.title.clone(),
|
||||
pick: Pick::Run(format!("/resume {}", m.path.display())),
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn first_prompt(p: &Path) -> Option<String> {
|
||||
let s = hx_core::session::Session::open(p).ok()?;
|
||||
s.messages().into_iter().find_map(|m| {
|
||||
(m.role == hx_ai::Role::User).then_some(())?;
|
||||
m.content.iter().find_map(|b| match b {
|
||||
hx_ai::ContentBlock::Text { text } => Some(
|
||||
text.lines()
|
||||
.next()
|
||||
.unwrap_or_default()
|
||||
.chars()
|
||||
.take(80)
|
||||
.collect(),
|
||||
),
|
||||
_ => None,
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
fn ago(t: SystemTime) -> String {
|
||||
let s = SystemTime::now()
|
||||
.duration_since(t)
|
||||
.unwrap_or_default()
|
||||
.as_secs();
|
||||
match s {
|
||||
0..60 => "just now".into(),
|
||||
60..3600 => format!("{}m ago", s / 60),
|
||||
3600..86400 => format!("{}h ago", s / 3600),
|
||||
_ => format!("{}d ago", s / 86400),
|
||||
.collect();
|
||||
if all.len() > SESSIONS {
|
||||
v.push(Entry {
|
||||
label: "more sessions…".into(),
|
||||
detail: format!("{} in this project", all.len()),
|
||||
pick: Pick::Run("/sessions".into()),
|
||||
});
|
||||
}
|
||||
v
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -0,0 +1,447 @@
|
||||
//! `/sessions` picker: filter, preview, scope toggle, delete.
|
||||
|
||||
use crate::theme;
|
||||
use crate::transcript::{Item, Transcript};
|
||||
use hx_core::session::{self, Meta};
|
||||
use ratatui::layout::{Constraint, Layout, Rect};
|
||||
use ratatui::text::{Line, Span};
|
||||
use ratatui::widgets::{Block, Borders, Clear, Paragraph};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::time::SystemTime;
|
||||
|
||||
pub enum Act {
|
||||
None,
|
||||
Close,
|
||||
Resume(PathBuf),
|
||||
}
|
||||
|
||||
pub struct Sessions {
|
||||
pub query: String,
|
||||
pub sel: usize,
|
||||
pub all_scope: bool,
|
||||
project: Vec<Meta>,
|
||||
all: Option<Vec<Meta>>,
|
||||
project_dir: PathBuf,
|
||||
root: PathBuf,
|
||||
current: PathBuf,
|
||||
/// pending delete confirmation
|
||||
pub confirm: Option<PathBuf>,
|
||||
preview: Option<(PathBuf, Vec<Line<'static>>)>,
|
||||
}
|
||||
|
||||
impl Sessions {
|
||||
/// `project_dir` = this project's session dir, `root` = `<hx home>/sessions`.
|
||||
pub fn new(project_dir: &Path, root: &Path, current: &Path) -> Self {
|
||||
Self {
|
||||
query: String::new(),
|
||||
sel: 0,
|
||||
all_scope: false,
|
||||
project: session::list(project_dir),
|
||||
all: None,
|
||||
project_dir: project_dir.into(),
|
||||
root: root.into(),
|
||||
current: current.into(),
|
||||
confirm: None,
|
||||
preview: None,
|
||||
}
|
||||
}
|
||||
|
||||
fn pool(&self) -> &[Meta] {
|
||||
match (&self.all, self.all_scope) {
|
||||
(Some(a), true) => a,
|
||||
_ => &self.project,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn matches(&self) -> Vec<&Meta> {
|
||||
let pool = self.pool();
|
||||
if self.query.is_empty() {
|
||||
return pool.iter().collect();
|
||||
}
|
||||
let keys: Vec<String> = pool
|
||||
.iter()
|
||||
.map(|m| {
|
||||
format!(
|
||||
"{} {}",
|
||||
m.title,
|
||||
if self.all_scope { &m.project } else { "" }
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
hx_core::command::rank(keys.iter().map(String::as_str), &self.query, usize::MAX)
|
||||
.into_iter()
|
||||
.filter_map(|k| keys.iter().position(|x| x == k).map(|i| &pool[i]))
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn selected(&self) -> Option<PathBuf> {
|
||||
self.matches().get(self.sel).map(|m| m.path.clone())
|
||||
}
|
||||
|
||||
pub fn toggle_scope(&mut self) {
|
||||
self.all_scope = !self.all_scope;
|
||||
if self.all_scope && self.all.is_none() {
|
||||
self.all = Some(session::list_all(&self.root));
|
||||
}
|
||||
self.sel = 0;
|
||||
}
|
||||
|
||||
fn reload(&mut self) {
|
||||
self.project = session::list(&self.project_dir);
|
||||
if self.all.is_some() {
|
||||
self.all = Some(session::list_all(&self.root));
|
||||
}
|
||||
self.sel = self.sel.min(self.matches().len().saturating_sub(1));
|
||||
self.preview = None;
|
||||
}
|
||||
|
||||
pub fn key(&mut self, k: crossterm::event::KeyEvent) -> Act {
|
||||
use crossterm::event::{KeyCode, KeyModifiers};
|
||||
let ctrl = k.modifiers.contains(KeyModifiers::CONTROL);
|
||||
if let Some(p) = self.confirm.take() {
|
||||
if matches!(k.code, KeyCode::Char('y' | 'Y')) {
|
||||
let _ = std::fs::remove_file(&p);
|
||||
self.reload();
|
||||
}
|
||||
return Act::None;
|
||||
}
|
||||
let n = self.matches().len().max(1);
|
||||
match k.code {
|
||||
KeyCode::Esc => return Act::Close,
|
||||
KeyCode::Char('c') if ctrl => return Act::Close,
|
||||
KeyCode::Char('d') if ctrl => {
|
||||
// the open session can't be deleted from under the agent
|
||||
self.confirm = self.selected().filter(|p| *p != self.current);
|
||||
}
|
||||
KeyCode::Tab => self.toggle_scope(),
|
||||
KeyCode::Up => self.sel = (self.sel + n - 1) % n,
|
||||
KeyCode::Down => self.sel = (self.sel + 1) % n,
|
||||
KeyCode::Backspace => {
|
||||
self.query.pop();
|
||||
self.sel = 0;
|
||||
}
|
||||
KeyCode::Char(c) if !ctrl => {
|
||||
self.query.push(c);
|
||||
self.sel = 0;
|
||||
}
|
||||
KeyCode::Enter => {
|
||||
if let Some(p) = self.selected() {
|
||||
return Act::Resume(p);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
Act::None
|
||||
}
|
||||
|
||||
pub fn draw(&mut self, f: &mut ratatui::Frame) {
|
||||
let th = theme::t();
|
||||
let a = f.area();
|
||||
let r = Rect::new(a.x + 1, a.y, a.width.saturating_sub(2), a.height);
|
||||
let scope = if self.all_scope {
|
||||
"this project ▸ all projects"
|
||||
} else {
|
||||
"this project ▸ all (tab)"
|
||||
};
|
||||
let ms: Vec<Meta> = self.matches().into_iter().cloned().collect();
|
||||
let block = Block::bordered().border_style(th.dim()).title(Span::styled(
|
||||
format!(" sessions · {scope} · {} ", ms.len()),
|
||||
th.dim(),
|
||||
));
|
||||
let inner = block.inner(r);
|
||||
f.render_widget(Clear, r);
|
||||
f.render_widget(block, r);
|
||||
let list_h = (ms.len() as u16).clamp(1, (inner.height / 2).max(3));
|
||||
let [q, _, list, sep, prev, help] = Layout::vertical([
|
||||
Constraint::Length(1),
|
||||
Constraint::Length(1),
|
||||
Constraint::Length(list_h),
|
||||
Constraint::Length(1),
|
||||
Constraint::Min(0),
|
||||
Constraint::Length(1),
|
||||
])
|
||||
.areas(inner);
|
||||
f.render_widget(
|
||||
Line::from(vec![
|
||||
Span::styled(format!("{} ", th.sym.user), th.accent()),
|
||||
Span::raw(self.query.clone()),
|
||||
]),
|
||||
q,
|
||||
);
|
||||
f.set_cursor_position((q.x + 2 + self.query.chars().count() as u16, q.y));
|
||||
|
||||
let top = self
|
||||
.sel
|
||||
.saturating_sub(list.height.saturating_sub(1) as usize);
|
||||
let w = list.width as usize;
|
||||
let rows: Vec<Line> = if ms.is_empty() {
|
||||
vec![Line::styled(" no sessions", th.dim())]
|
||||
} else {
|
||||
ms.iter()
|
||||
.enumerate()
|
||||
.skip(top)
|
||||
.take(list.height as usize)
|
||||
.map(|(i, m)| self.row(m, i == self.sel, w))
|
||||
.collect()
|
||||
};
|
||||
f.render_widget(Paragraph::new(rows), list);
|
||||
f.render_widget(
|
||||
Block::new().borders(Borders::TOP).border_style(th.dim()),
|
||||
sep,
|
||||
);
|
||||
|
||||
if let Some(m) = ms.get(self.sel) {
|
||||
if self.preview.as_ref().is_none_or(|(p, _)| *p != m.path) {
|
||||
self.preview = Some((m.path.clone(), preview(&m.path, prev.width)));
|
||||
}
|
||||
if let Some((_, ls)) = &self.preview {
|
||||
let skip = ls.len().saturating_sub(prev.height as usize);
|
||||
f.render_widget(Paragraph::new(ls[skip..].to_vec()), prev);
|
||||
}
|
||||
}
|
||||
let help_text = match &self.confirm {
|
||||
Some(p) => Line::styled(format!("delete {}? [y/n]", p.display()), th.warn()),
|
||||
None => Line::styled(
|
||||
"enter resume · tab scope · ctrl-d delete · esc close",
|
||||
th.dim(),
|
||||
),
|
||||
};
|
||||
f.render_widget(help_text, help);
|
||||
}
|
||||
|
||||
fn row(&self, m: &Meta, sel: bool, w: usize) -> Line<'static> {
|
||||
let th = theme::t();
|
||||
let st = if sel { th.sel() } else { th.plain() };
|
||||
let dim = if sel { st } else { th.dim() };
|
||||
let mark = if sel { th.sym.more } else { " " };
|
||||
let cur = if m.path == self.current { "●" } else { " " };
|
||||
let fork = if m.branches > 1 {
|
||||
format!("⑂{} ", m.branches)
|
||||
} else {
|
||||
String::new()
|
||||
};
|
||||
let tail = if self.all_scope {
|
||||
m.project.clone()
|
||||
} else {
|
||||
m.model.clone().unwrap_or_default()
|
||||
};
|
||||
let tail = tail.strip_prefix("claude-").unwrap_or(&tail);
|
||||
let right = format!("{fork}{:>4} msg {:<16}", m.messages, cut(tail, 16));
|
||||
let left = format!("{mark}{cur} {:<9} ", ago(m.modified));
|
||||
let room = w.saturating_sub(left.chars().count() + right.chars().count() + 1);
|
||||
let title = cut(&m.title, room);
|
||||
let pad = room.saturating_sub(title.chars().count());
|
||||
Line::from(vec![
|
||||
Span::styled(left, dim),
|
||||
Span::styled(title, st),
|
||||
Span::styled(" ".repeat(pad + 1), st),
|
||||
Span::styled(right, dim),
|
||||
])
|
||||
}
|
||||
}
|
||||
|
||||
fn cut(s: &str, n: usize) -> String {
|
||||
if s.chars().count() <= n {
|
||||
return s.into();
|
||||
}
|
||||
let mut t: String = s.chars().take(n.saturating_sub(1)).collect();
|
||||
t.push('…');
|
||||
t
|
||||
}
|
||||
|
||||
/// Transcript lines of a session, for the preview pane.
|
||||
fn preview(p: &Path, width: u16) -> Vec<Line<'static>> {
|
||||
let Ok(s) = session::Session::open(p) else {
|
||||
return vec![];
|
||||
};
|
||||
let mut t = Transcript::default();
|
||||
history(&mut t, &s.messages());
|
||||
t.lines(false, width)
|
||||
}
|
||||
|
||||
/// Rebuild transcript items from stored messages: text, and tool calls with their results.
|
||||
pub fn history(t: &mut Transcript, msgs: &[hx_ai::Message]) {
|
||||
use hx_ai::{ContentBlock as B, Role};
|
||||
for m in msgs {
|
||||
for b in &m.content {
|
||||
match (m.role, b) {
|
||||
(Role::User, B::Text { text }) => t.push(Item::User(text.clone())),
|
||||
(Role::Assistant, B::Text { text }) => t.push(Item::Assistant(text.clone())),
|
||||
(Role::Assistant, B::ToolUse { id, name, input }) => t.push(Item::Tool {
|
||||
id: id.clone(),
|
||||
name: name.clone(),
|
||||
args: input.clone(),
|
||||
result: None,
|
||||
started: std::time::Instant::now(),
|
||||
took: None,
|
||||
}),
|
||||
(
|
||||
Role::User,
|
||||
B::ToolResult {
|
||||
tool_use_id,
|
||||
content,
|
||||
is_error,
|
||||
},
|
||||
) => {
|
||||
if let Some(Item::Tool { result, .. }) = t
|
||||
.items
|
||||
.iter_mut()
|
||||
.rev()
|
||||
.find(|i| matches!(i, Item::Tool { id, .. } if id == tool_use_id))
|
||||
{
|
||||
*result = Some((content.clone(), *is_error));
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn ago(t: SystemTime) -> String {
|
||||
let s = SystemTime::now()
|
||||
.duration_since(t)
|
||||
.unwrap_or_default()
|
||||
.as_secs();
|
||||
match s {
|
||||
0..60 => "just now".into(),
|
||||
60..3600 => format!("{}m ago", s / 60),
|
||||
3600..86400 => format!("{}h ago", s / 3600),
|
||||
86400..172800 => "yesterday".into(),
|
||||
_ => format!("{}d ago", s / 86400),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
|
||||
use hx_ai::{ContentBlock, Message, Role};
|
||||
use ratatui::backend::TestBackend;
|
||||
use serde_json::json;
|
||||
|
||||
fn k(c: KeyCode) -> KeyEvent {
|
||||
KeyEvent::new(c, KeyModifiers::NONE)
|
||||
}
|
||||
|
||||
fn seed(root: &Path) -> (PathBuf, PathBuf) {
|
||||
let proj = root.join("proj");
|
||||
let mut a = session::Session::open(proj.join("1.jsonl")).unwrap();
|
||||
a.append(Message::user("parser: handle trailing commas"))
|
||||
.unwrap();
|
||||
a.append_by(
|
||||
Message {
|
||||
role: Role::Assistant,
|
||||
content: vec![
|
||||
ContentBlock::Text {
|
||||
text: "Fixing the grammar.".into(),
|
||||
},
|
||||
ContentBlock::ToolUse {
|
||||
id: "t1".into(),
|
||||
name: "edit".into(),
|
||||
input: json!({"path": "src/parse.rs"}),
|
||||
},
|
||||
],
|
||||
},
|
||||
Some("opus".into()),
|
||||
)
|
||||
.unwrap();
|
||||
a.append(Message {
|
||||
role: Role::User,
|
||||
content: vec![ContentBlock::ToolResult {
|
||||
tool_use_id: "t1".into(),
|
||||
content: "edited\n+a\n-b".into(),
|
||||
is_error: false,
|
||||
}],
|
||||
})
|
||||
.unwrap();
|
||||
std::thread::sleep(std::time::Duration::from_millis(20));
|
||||
let mut b = session::Session::open(proj.join("2.jsonl")).unwrap();
|
||||
b.append(Message::user("review PR 73")).unwrap();
|
||||
std::thread::sleep(std::time::Duration::from_millis(20));
|
||||
let mut c = session::Session::open(root.join("other/3.jsonl")).unwrap();
|
||||
c.append(Message::user("elsewhere")).unwrap();
|
||||
(proj.join("1.jsonl"), proj.join("2.jsonl"))
|
||||
}
|
||||
|
||||
fn screen(s: &mut Sessions, w: u16, h: u16) -> Vec<String> {
|
||||
let mut term = ratatui::Terminal::new(TestBackend::new(w, h)).unwrap();
|
||||
term.draw(|f| s.draw(f)).unwrap();
|
||||
let buf = term.backend().buffer().clone();
|
||||
(0..h)
|
||||
.map(|y| (0..w).map(|x| buf[(x, y)].symbol().to_string()).collect())
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn filter_preview_scope_delete() {
|
||||
let t = tempfile::tempdir().unwrap();
|
||||
let (first, second) = seed(t.path());
|
||||
let mut s = Sessions::new(&t.path().join("proj"), t.path(), &second);
|
||||
let titles = |s: &Sessions| {
|
||||
s.matches()
|
||||
.iter()
|
||||
.map(|m| m.title.clone())
|
||||
.collect::<Vec<_>>()
|
||||
};
|
||||
assert_eq!(
|
||||
titles(&s),
|
||||
["review PR 73", "parser: handle trailing commas"]
|
||||
);
|
||||
|
||||
for c in "pars".chars() {
|
||||
s.key(k(KeyCode::Char(c)));
|
||||
}
|
||||
assert_eq!(titles(&s), ["parser: handle trailing commas"]);
|
||||
let rows = screen(&mut s, 100, 20);
|
||||
let all = rows.join("\n");
|
||||
assert!(
|
||||
rows[0].contains("sessions · this project ▸ all (tab) · 1"),
|
||||
"{all}"
|
||||
);
|
||||
assert!(rows[1].contains("❯ pars"), "{all}");
|
||||
assert!(
|
||||
rows[3].contains("▸ just now parser: handle trailing commas")
|
||||
&& rows[3].contains("3 msg opus"),
|
||||
"{all}"
|
||||
);
|
||||
assert!(
|
||||
all.contains("❯ parser: handle trailing commas"),
|
||||
"preview: {all}"
|
||||
);
|
||||
assert!(
|
||||
all.contains("✓ edit src/parse.rs"),
|
||||
"preview tool line: {all}"
|
||||
);
|
||||
assert!(rows[18].contains("enter resume · tab scope"), "{all}");
|
||||
|
||||
// all projects scope shows the project column
|
||||
s.query.clear();
|
||||
s.key(k(KeyCode::Tab));
|
||||
assert_eq!(titles(&s)[0], "elsewhere");
|
||||
let rows = screen(&mut s, 100, 20);
|
||||
assert!(
|
||||
rows[3].contains("elsewhere") && rows[3].contains("other"),
|
||||
"{rows:#?}"
|
||||
);
|
||||
s.key(k(KeyCode::Tab));
|
||||
|
||||
// current session is marked and can't be deleted; others need y
|
||||
let rows = screen(&mut s, 100, 20);
|
||||
assert!(rows[3].contains("▸● just now review PR 73"), "{rows:#?}");
|
||||
s.key(KeyEvent::new(KeyCode::Char('d'), KeyModifiers::CONTROL));
|
||||
assert!(s.confirm.is_none());
|
||||
s.key(k(KeyCode::Down));
|
||||
s.key(KeyEvent::new(KeyCode::Char('d'), KeyModifiers::CONTROL));
|
||||
assert_eq!(s.confirm.as_ref(), Some(&first));
|
||||
assert!(screen(&mut s, 100, 20)[18].contains("[y/n]"));
|
||||
s.key(k(KeyCode::Char('n')));
|
||||
assert!(first.exists());
|
||||
s.key(KeyEvent::new(KeyCode::Char('d'), KeyModifiers::CONTROL));
|
||||
s.key(k(KeyCode::Char('y')));
|
||||
assert!(!first.exists());
|
||||
assert_eq!(titles(&s), ["review PR 73"]);
|
||||
assert!(matches!(s.key(k(KeyCode::Enter)), Act::Resume(p) if p == second));
|
||||
assert!(matches!(s.key(k(KeyCode::Esc)), Act::Close));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user